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??

(そしてそれは同じように続きます)

次のように(jQueryを使用して)ajax呼び出しを試みます。

$.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);
}

今回は有効な JSON を取得しました (Jsonlint によると) が、ヘッダーは application/json ではありません... (JsonResponse ではなく Response を送信しているので意味があります...) (しかし、それは私が避けようとしているものです) 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 が有効である限り、content-type が application/json ではなく text/html であることは「本当に重要」ではありません。JS が再生されなかった理由は、val.msgbody などの val のプロパティではなく、val を要求していたためです。:

だから私の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 に答える
-2

問題は、配列ではなく文字列を JsonResponse に渡していることです。

コントローラーのコードは次のとおりです。

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

コントローラコードは次のようにする必要があります

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