How can I send JSON response in symfony2 controller
Symfony 2.1
$response = new Response(json_encode(array('name' => $name)));$response->headers->set('Content-Type', 'application/json');return $response;
Symfony 2.2 and higher
You have special JsonResponse class, which serialises array to JSON:
return new JsonResponse(array('name' => $name));
But if your problem is How to serialize entity then you should have a look at JMSSerializerBundle
Assuming that you have it installed, you'll have simply to do
$serializedEntity = $this->container->get('serializer')->serialize($entity, 'json');return new Response($serializedEntity);
You should also check for similar problems on StackOverflow:
Symfony 2.1 has a JsonResponse class.
return new JsonResponse(array('name' => $name));
The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.
There is also a handy setCallback
function for JSONP.
Since Symfony 3.1 you can use JSON Helperhttp://symfony.com/doc/current/book/controller.html#json-helper
public function indexAction(){// returns '{"username":"jane.doe"}' and sets the proper Content-Type headerreturn $this->json(array('username' => 'jane.doe'));// the shortcut defines three optional arguments// return $this->json($data, $status = 200, $headers = array(), $context = array());}