简体   繁体   中英

List of entites not converting to json instead I get an array of empty objects

I have the following code:

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);
}

which returns the following, notice the array of empty objects

{ "items": [ {}, {}, {}, {}, {}, {}, {}, {}, {} ], "count_results": 9, "current_page": 1, "number_of_pages": 1, "next": null, "prev": null, "paginate": false }

I know their properties aren't null by doing this:

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

// returns 'Documentary 1'

The problem is most likely that your $item object is not json serializable.

Try implementing the JsonSerializable interface in that class( https://www.php.net/manual/en/class.jsonserializable.php ) and add a method to your item class like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM