【发布时间】:2015-11-25 13:30:40
【问题描述】:
您好,我正在尝试使用 symfony2 生成 json 作为响应。
这是我的代码。
/**
* @Route("/viewComments/{taskId}")
*
*/
public function viewCommentsAction($taskId)
{
$commentsList = $this->getDoctrine()->getRepository("AppBundle:Comments")
->findBy(array("task" => $taskId));
if (!$commentsList) {
throw $this->createNotFoundException("non comments to show");
}
$serializer = $this->get('serializer');
$json = $serializer->serialize(
$commentsList,
'json', array('groups' => array('group1'))
);
return new Response($json);
}
很遗憾,我收到了回复:
[[],[],[],[]]
有什么建议吗?
【问题讨论】:
-
您的
app/config/config.yml中是否激活了serializer? -
序列化组件作用于对象。我猜你正在传递一个对象数组。您将需要更多代码将每个单独的对象序列化为数组,将数组组合成一个大数组,然后使用 JsonResponse 对象。
-
嗨 scoolnico,序列化程序已激活 app/config/config.yml 序列化程序:{ enable_annotations: true }
-
嗨 Cerad,我 var_dump($cmetsList);我看到一个包含 4 个对象的数组。