本文介绍了\u0022 而不是 ""使用 JsonResponse symfony的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:返回的数据有 \u0022 而不是 "".

my problem is :The data returned have \u0022 instead of "".

$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}]"

预先感谢您的帮助

推荐答案

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

As your entities are already serialised, change your JsonResponse to a Response :

use Symfony\Component\HttpFoundation\Response;

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

return $response;

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

Or decode your results before create your JsonResponse :

return new JsonResponse(json_decode($jsonContent));

注意JsonResponseContent-Type自动为application/json,无需设置.

Note that the Content-Type of a JsonResponse is automatically application/json, no need to set it.

这篇关于\u0022 而不是 ""使用 JsonResponse symfony的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 23:29