\ u0022而不是“”与JsonResponse symfony

时间:2016-03-13 17:12:15

标签: symfony

我的问题是: 返回的数据有\ u0022而不是“”。

$em=$this->getDoctrine()->getManager();
$result = $em->getRepository('HomeBundle:Product')->findAll();

$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);

$jsonContent = $serializer->serialize($result,'json');

$response = new JsonResponse($jsonContent);
$response->headers->set('Content-Type', 'application/json');
return $response;

这就是我得到的

"[{\u0022id\u0022:1,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:3},{\u0022id\u0022:2,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:5},{\u0022id\u0022:3,\u0022name\u0022:\u0022oppv\u0022,\u0022price\u0022:16},{\u0022id\u0022:4,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:6},{\u0022id\u0022:5,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:7},{\u0022id\u0022:6,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:34},{\u0022id\u0022:7,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:56},{\u0022id\u0022:8,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:30}]"

提前感谢您的帮助

1 个答案:

答案 0 :(得分:8)

由于您的实体已经序列化,请将JsonResponse更改为Response

use Symfony\Component\HttpFoundation\Response;

// ...
$response = new Response($jsonContent);
$response->headers->set('Content-Type', 'application/json');

return $response;

或在创建JsonResponse之前解码您的搜索结果:

return new JsonResponse(json_decode($jsonContent));

请注意,Content-Type的{​​{1}}会自动JsonResponse,无需进行设置。