Return a JSON array from a Controller in Symfony

后端 未结 7 947
一个人的身影
一个人的身影 2020-12-17 14:30

I am trying return a JSON response from a controller in Symfony 2. Form example, in Spring MVC I can get a JSON response with @ResponseBody annotattion. I want get a JSON re

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 14:49

    Following the best practices, I managed to do it the following way:

    public function index(CityRepository $cityRepository,
                          SerializerInterface $serializer): Response 
    

    Injecting repository & serializer.

    $cities = $cityRepository->findAll();
    

    Retrieving an array of objects.

    $data = $serializer->serialize($cities, 'json');
    

    Serializing the data into a JSON string.

    return new JsonResponse($data, 200, [], true);
    

    Passing the JSON string to JsonResponse.

提交回复
热议问题