不转换为json的实体列表,但我得到了一个空对象数组

时间:2019-07-10 12:24:30

标签: php symfony symfony4 fosrestbundle pagerfanta

我有以下代码:

public function adminListAction(Request $request)
    {
        if (!$this->isGranted('ROLE_ADMIN')) {
            return new JsonResponse("Not granted");
        }

        $page = $request->query->get('page', 1);

        $criteria = new DocumentaryCriteria();
        $criteria->setStatus(DocumentaryStatus::PUBLISH);
        $criteria->setSort([
            DocumentaryOrderBy::CREATED_AT => Order::DESC
        ]);

        $qb = $this->documentaryService->getDocumentariesByCriteriaQueryBuilder($criteria);

        $adapter = new DoctrineORMAdapter($qb, false);
        $pagerfanta = new Pagerfanta($adapter);
        $pagerfanta->setMaxPerPage(12);
        $pagerfanta->setCurrentPage($page);

        $items = (array) $pagerfanta->getCurrentPageResults();

        $data = [
            'items'             => $items,
            'count_results'     => $pagerfanta->getNbResults(),
            'current_page'      => $pagerfanta->getCurrentPage(),
            'number_of_pages'   => $pagerfanta->getNbPages(),
            'next'              => ($pagerfanta->hasNextPage()) ? $pagerfanta->getNextPage() : null,
            'prev'              => ($pagerfanta->hasPreviousPage()) ? $pagerfanta->getPreviousPage() : null,
            'paginate'          => $pagerfanta->haveToPaginate(),
        ];

        return new JsonResponse($data);
    }

返回以下内容,请注意空对象的数组

  

{   “项目”:[          {},          {},          {},          {},          {},          {},          {},          {},          {}      ],      “ count_results”:9      “当前页”:1      “页数”:1      “ next”:null,      “ prev”:null,      “分页”:false   }

通过这样做,我知道它们的属性不为空

foreach ($items as $item) {
    echo $item->getTitle();
}

//返回“纪录片1”

1 个答案:

答案 0 :(得分:0)

问题很可能是您的$item对象不可json序列化的。

尝试在该类(https://www.php.net/manual/en/class.jsonserializable.php)中实现JsonSerializable接口,并向您的item类添加方法,如下所示:

public function jsonSerialize() { return [ 'title' => $this->getTitle(), 'foo' => $this->bar(), ]; }