2012-05-14 7 views
0

これは私のコントローラはsymfonyでJSONを返すことができない2

public function index2Action($name) 
    { 
    $em = $this->getDoctrine()->getEntityManager(); 
    $test = $em->getRepository('RestWebServiceBundle:Test')->findall(); 
    return new Response(json_encode(array('locations' => $test))); 

    } 

ですJSONを入手してください。

私は間違っていますか?私は最初のシナリオでJSONを取得しようとしています。

UPDATE:私は$テスト変数が実際に空でないことを確認したと、私はそれにしますprint_rを行うとき、それは私に次のことを示しています

Array 
(
    [0] => Rest\WebServiceBundle\Entity\Test Object 
     (
      [id:protected] => 1 
      [title:protected] => test title 
      [author:protected] => test author 
      [blog:protected] => this is the blog 
      [tags:protected] => 
      [comments:protected] => 
      [created:protected] => DateTime Object 
       (
        [date] => 2012-05-13 00:00:00 
        [timezone_type] => 3 
        [timezone] => America/Chicago 
       ) 

      [updated:protected] => DateTime Object 
       (
        [date] => 2012-05-13 00:00:00 
        [timezone_type] => 3 
        [timezone] => America/Chicago 
       ) 

     ) 

) 
null 
+0

チェックを動作します。最初の例では、あなたはjsonを取り戻しています。 PHPはあなたが言うことだけを出力することができ、おそらく$ testは空のオブジェクトとして戻ってきます。だから...理由を見つけ出す。 –

+0

テストで有効なレコードセットを取得していることを確認しました。 json_encodeとの関係は、findallの結果セットが好きではないような感じです。 – jini

+0

json-encodeはオブジェクトを変換しますが、そのオブジェクトが "stringify"メソッドを提供する場合に限ります。 –

答えて

2

私は非常にあなたのためにシリアライザを使用することをお勧めしますエンティティを返す。シリアライザコンポーネントまたはjmsserializerbundleを見てください。

0
 $obj = $test; 

     $serializer = new Serializer(
      array(new GetSetMethodNormalizer()), 
      array('json' => new JsonEncoder()) 
     ); 
     $json = $serializer->serialize($obj, 'json'); 

     $response = new \Symfony\Component\HttpFoundation\Response($json); 
     $response->headers->set('Content-Type', 'application/json'); 
     return $response; 
0

は、私は私のリポジトリクラスの代わりにgetResult()の)getArrayResultを(使用してこれを試してみた&それは$テストが戻って空に来ている理由

+0

@gunarなぜこれは(少なくとも試みる)答えではないと思いますか? –

+0

@MathiasMüller:これをもう一度読み返してください。投票は取り消されます。気づいてくれてありがとう! – gunar

関連する問題