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:

  • How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?
  • Symfony 2 Doctrine export to JSON

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)