";序列化数据中不支持资源";使用FOSRestBundle和传呼机时


"Resources are not supported in serialized data." when using FOSRestBundle and Paginator

我正在使用FOSRestBundle和JMSSerializerBundle为我的网站设置REST服务。

我在实体存储库上创建了一个自定义方法,该方法返回一个分页器对象。当我在普通网站上使用该方法时,该方法效果很好,但当我想将该方法与REST路由一起使用时,会抛出此错误(XML或JSON输出会抛出相同的错误):

"序列化数据中不支持资源。"

我真的不知道在哪里搜索,因为错误对我来说不是很明显。

这是我的AdsRestController.php:

<?php
namespace MyProject'MainBundle'Controller;
use Symfony'Bundle'FrameworkBundle'Controller'Controller;
use FOS'RestBundle'Controller'Annotations'View;
use FOS'RestBundle'Controller'Annotations'Get;

class AdsRestController extends Controller
{
    /**
     * @View
     * @Get("/ads/list/all/{page}", requirements={"page" = "'id+"}, defaults={"page" = 1})
     */
    public function getAdsListAllAction($page) {
        $theAds = $this->getDoctrine()->getRepository('MyProjectMainBundle:Ads')->getAds($page);
        return $theAds;
    }
}

和我的AdsRepository.php:

<?php
namespace MyProject'MainBundle'Entity;
use Doctrine'ORM'EntityRepository;
use Doctrine'ORM'Tools'Pagination'Paginator;
class AdsRepository extends EntityRepository
{
    public function getAds($page=1, $maxPerPage=10)
    {
            $query = $this->createQueryBuilder('a')
                ->orderBy('a.date', $order)
            ;
        $query->getQuery();
        $query
            ->setFirstResult(($page-1) * $maxPerPage)
            ->setMaxResults($maxPerPage)
        ;
        return new Paginator($query, true);
    }
}

如有任何帮助,我们将不胜感激!

谢谢。

您可以使用iterator_to_array将分页器的迭代器转换为数组:

return iterator_to_array($theAds->getIterator());

在rest控制器中使用getAds()->toArray()手动将结果转换为数组。

已在此处回答,请使用搜索!

查看Paginator对象上可用的->getIterator()方法。看见https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Tools/Pagination/Paginator.php

如果使用iterator_to_array,它将把结果数组转换为单个对象。最好将它们提取到数组中,然后对其进行序列化

 $var = [];
        foreach ($records as $rec){
            array_push($var, $rec);
        }
        $res = $this->get('jms_serializer')->serialize($var, 'json');
        return new JsonResponse(json_decode($res));