0

这是我的控制器

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

    }

当我转到 URL 时,我得到:

{"locations":[{}]}

但是,当我使用:

public function index2Action($name)
    {   
$name ="Adam";
  return new Response(json_encode(array('locations' => $name)));

    }

我得到了 JSON。

我究竟做错了什么?我正在尝试在第一种情况下获取 JSON。

更新:我已经验证 $test 变量确实不为空,当我对其执行 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
4

3 回答 3

2

我强烈建议您将序列化程序用于返回实体。查看序列化程序组件或 jmsserializerbundle。

于 2012-05-14T07:48:37.110 回答
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;
于 2013-06-14T09:36:54.917 回答
0

我已经通过在我的存储库类中使用 getArrayResult() 而不是 getResult() 进行了尝试,它可以工作

于 2014-03-26T08:56:55.830 回答