且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 symfony2 控制器中发送 JSON 响应

更新时间:2023-11-19 18:54:22

Symfony 2.1

$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');

return $response;

Symfony 2.2 及更高版本

您有特殊的 JsonResponse将数组序列化为 JSON 的类:

You have special JsonResponse class, which serialises array to JSON:

return new JsonResponse(array('name' => $name));

但如果你的问题是如何序列化实体,那么你应该看看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 ***: