【问题标题】:symfony2 creating json from objectsymfony2 从对象创建 json
【发布时间】: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 个对象的数组。

标签: php json symfony


【解决方案1】:

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

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

        return $query->getArrayResult();
    }
}

如您所见,我返回一个数组,现在您可以看到响应中的值。 稍后,更改 Action Controller 中的下一行:

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

注意:你应该用单数来称呼你的实体

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2019-06-02
    • 2014-07-12
    • 1970-01-01
    • 2019-05-05
    • 2020-07-10
    • 2019-08-04
    相关资源
    最近更新 更多