drdzpknk76046 2015-11-25 13:30
浏览 66
已采纳

symfony2从object创建json

Hi I am trying to generate json as response using symfony2.

Here is my code.

/**
 * @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);

}

unfortunately I am getting response:

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

Any suggestions?

  • 写回答

1条回答 默认 最新

  • douniani679741 2015-11-25 15:38
    关注

    Try this, creates a file: CommentRepository

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

    as you can see, I return an Array and now you can see values on the response. Later, changes the next line in your Action Controller:

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

    Note: You should call your entities in singular

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码