问题
I am setting up a REST service for my website with the FOSRestBundle and JMSSerializerBundle.
I made a custom method on a entity repository which returns a Paginator object. The method works great when I use it on the normal website, but when I want to use the method with the REST route, this error is thrown (XML or JSON output throws the same error) :
"Resources are not supported in serialized data."
I really don't know where to search since the error isn't very explicit to me.
Here's my 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;
}
}
and my 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);
}
}
Any help would be highly appreciated !
Thanks.
回答1:
You can use iterator_to_array
to convert iterator of your paginator into array :
return iterator_to_array($theAds->getIterator());
回答2:
Convert result manually to an array by using getAds()->toArray() in your rest controller.
already answered here, use the search!
回答3:
Check out the ->getIterator() method available on Paginator objects. See https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Tools/Pagination/Paginator.php
回答4:
If you use iterator_to_array
, it will convert the result array to a single object. It is better to fetch them to an array and then serialize it.
$var = [];
foreach ($records as $rec){
array_push($var, $rec);
}
$res = $this->get('jms_serializer')->serialize($var, 'json');
return new JsonResponse(json_decode($res));
来源:https://stackoverflow.com/questions/28389046/resources-are-not-supported-in-serialized-data-when-using-fosrestbundle-and-p