这是我的控制器方法:
public function sendjsonAction()
{
$message = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Message')
->findAll();
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('message' => new
JsonEncoder()));
$message = $serializer->serialize($message, 'json');
return new JsonResponse($message);
}
这是我的路由器:
acme_store_sendjson:
pattern: /sendjson/
defaults: { _controller: AcmeStoreBundle:Default:sendjson}
这是我去/ sendjson /时所得到的:
"[{\u0022id\u0022:1,\u0022iam\u0022:1,\u0022youare\u0022:2,\u0022lat\u0022:50.8275853,\u0022lng\u0022:4.3809764,\u0022date\u0022:{\u0022lastErrors\u0022:{\u0022warning_count\u0022:0,\u0022warnings\u0022:[],\u0022error_count\u0022:0,\u0022errors\u0022:[]},\u0022timezone\u0022:{\u0022name\u0022:\u0022UTC\u0022,\u0022location\u0022:{\u0022country_code\u0022:\u0022??
(同样地继续)
我尝试使用以下内容进行ajax调用(使用jQuery):
$.getJSON('/app_dev.php/sendjson', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
我得到了
Uncaught TypeError: Cannot use 'in' operator to search for '1549' in [{"id":1,...
当我更改Symfony2的响应类型时,我得到一个
列表[对象] [对象] [对象] [对象] [对象] [对象] ...
我做错了什么?我应该解析将\ u0022转换为“或者从一开始我的反应是否错误?”
修改
我还尝试将控制器更改为:
public function sendjsonAction()
{
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$message = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Message')
->findAll();
$serializer = $serializer->serialize($message, 'json');
return new Response($serializer);
}
这次我获得了VALID JSON,(根据Jsonlint)buuttt标题不是application / json ...(有道理因为我发送了一个Response而不是JsonResponse ......)(但那就是我在尝试避免因为JsonResponse似乎正在改变添加奇怪的字符)
[{"id":1,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"},{"id":2,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"},{"id":3,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"},{"id":4,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"},{"id":5,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"},{"id":6,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"}]
答案 0 :(得分:4)
我找到了答案。
1)只要JSON是有效的,内容类型不是application / json而是text / html并不“真正重要”。我的JS没有玩的原因是我要求val而不是val的属性,例如val.msgbody。 :
所以我的Javascript应该是
$.getJSON('/app_dev.php/sendjson', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val.msgbody + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
如果要求Content-Type,那么控制器可能是这样的:
public function sendjsonAction()
{
$encoders = array(new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$message = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Message')
->findAll();
$response = new Response($serializer->serialize($message, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
答案 1 :(得分:2)
序列化是规范化的过程 - 创建一个表示对象的数组 - 并对该表示进行编码(即对JSON或XML)。 JsonResponse为您处理编码部分(查看类的名称),因此您无法传递“序列化对象”,否则将再次编码。 因此,解决方案只是规范化对象并将其传递给JsonResponse:
public function indexAction($id)
{
$repository = $this->getDoctrine()->getRepository('MyBundle:Product');
$product = $repository->find($id);
$normalizer = new GetSetMethodNormalizer();
$jsonResponse = new JsonResponse($normalizer->normalize($product));
return $jsonResponse;
}
答案 2 :(得分:0)
您可以仅使用规范化器而不使用序列化器来解决此问题:
$normalizer = new ObjectNormalizer();
$array = $normalizer->normalize($newEntry);
$entryJSONFile = json_encode($array, JSON_UNESCAPED_UNICODE);
答案 3 :(得分:0)
https://www.php.net/manual/en/json.constants.php
https://www.php.net/manual/en/function.json-encode.php
要输出JSON字符串的对象\Symfony\Component\HttpFoundation\JsonResponse
使用函数json_encode
,通过对象setEncodingOptions
的方法,您可以按JSON_UNESCAPED_UNICODE
之类的按位常量设置输出JSON字符串选项:
按字面意义编码多字节Unicode字符(默认为转义为\ uXXXX)。自PHP 5.4.0起可用。
$jsonResponse = new \Symfony\Component\HttpFoundation\JsonResponse($arrayForJSON);
$jsonResponse->setEncodingOptions($this->getEncodingOptions()|JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK|JSON_PRETTY_PRINT);
$jsonResponse->send();
答案 4 :(得分:0)
您的代码两次在json中编码。当您使用序列化程序自己进行json编码时,请使用Response类。
将返回新的JsonResponse($ message)替换为返回新的Response($ message)
答案 5 :(得分:-2)
问题是您是将字符串传递给JsonResponse而不是数组。
您的控制器代码是:
...
return new JsonResponse($message)
...
您的控制器代码必须是:
...
return new JsonResponse(json_decode($message, true))
...