Return a JSON array from a Controller in Symfony

后端 未结 7 948
一个人的身影
一个人的身影 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:40

    You need to change your code this way:

    /**
     * @Route(
     *      "/drop/getCategory/",
     *      name="getCategory"
     * )
     * @Method("GET")
     */
    public function getAllCategoryAction() {
        $categorias = $this->getDoctrine()
                           ->getRepository('AppBundle:Categoria')
                           ->findAll();
    
        $categorias = $this->get('serializer')->serialize($categorias, 'json');
    
        $response = new Response($categorias);
    
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    

    If the serializer service is not enabled, you have to enable it in app/config/config.yml:

        framework:
            # ...
            serializer:
                enabled: true
    

    For more advanced options for serialization, you can install JMSSerializerBundle

提交回复
热议问题