这是我的控制器
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
答案 0 :(得分:2)
我强烈建议您将序列化程序用于返回实体。看看序列化程序组件或jmsserializerbundle。
答案 1 :(得分: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;
答案 2 :(得分:0)
我在我的存储库类&中使用了getArrayResult()而不是getResult()来尝试这个。它的工作原理