2015-11-25 147 views
1

您好我正在尝试使用symfony2生成json作为响应。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); 

} 

不幸的是我得到的回应:

[[],[],[],[]] 

有什么建议?

+0

在你的'应用程序/配置/ config.yml'激活'serializer'? – scoolnico

+1

序列化组件对对象起作用。我猜你正在传入一组对象。您需要更多的代码来将每个单独的对象序列化为数组,然后将这些数组组合成一个大数组,然后使用JsonResponse对象。 – Cerad

+0

hi scoolnico序列化器已激活app/config/config.yml序列化器:{enable_annotations:true} – Filip

回答

0

试试这个,创建一个文件:CommentRepository

class CommentRepository extends EntityRepository 
{ 
    public function findCommentsList($id) 
    { 
     $query = $this->getEntityManager()->createQuery('YOUR QUERY HERE'); 
     ... 

     return $query->getArrayResult(); 
    } 
} 

,你可以看到,我返回数组,现在你可以看到在响应值。 后来改变了下一行在动作控制器:

... 
$commentsList = $this->getDoctrine()->getRepository("AppBundle:Comments") 
             ->findCommentsList($taskId)); 
... 

注:你应该打电话给你的实体奇异

+0

嗨rck6982它的工作!非常感谢 :) – Filip