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
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