4

这是我的控制器方法:

  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)但标头不是 application/json ...(这是有道理的,因为我发送的是响应而不是 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!"}]
4

6 回答 6

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;
  }
于 2013-02-11T17:30:23.847 回答
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;
}
于 2014-04-04T18:28:19.743 回答
1

您可以只使用没有序列化器的规范化器来解决这个问题:

    $normalizer = new ObjectNormalizer();
    $array = $normalizer->normalize($newEntry);
    $entryJSONFile = json_encode($array, JSON_UNESCAPED_UNICODE);
于 2018-08-27T08:40:31.037 回答
1

您的代码在 json 中编码两次。当您使用序列化程序自己进行 json 编码时,请使用 Response 类。

将 return new JsonResponse($message) 替换为 return new Response($message)

于 2020-03-07T11:43:27.660 回答
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 字符串选项,例如JSON_UNESCAPED_UNICODE

对多字节 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();
于 2019-10-15T08:39:56.573 回答
-2

问题是您将字符串传递给 JsonResponse 而不是数组。

您的控制器代码是:

...
return new JsonResponse($message)
...

您的控制器代码必须是:

...
return new JsonResponse(json_decode($message, true))
...
于 2014-02-02T17:27:03.753 回答