我一直在使用“jms / serializer”:“0.13.*@dev”来序列化我的对象。
我在Zend Framework(2)和Doctrine项目中使用它。
这是我的代码:
use JMS\Serializer\SerializerBuilder as SerializerBuilder;
(....)
public function getList() {
$em = $this->getEntityManager();
$repo = $em->getRepository('MyApp\Entity\Product');
$hydrator = new DoctrineHydrator($em);
$data = array();
foreach ($repo->findAll() as $found) {
$data[] = $hydrator->extract($found);
}
$serializer = SerializerBuilder::create()->build();
$jsonContent = $serializer->serialize($data, 'json');
$this->getResponseWithHeader()->setStatusCode(self::OK_200);
return new JsonModel($jsonContent);
}
但是我收到了这个错误:
序列化数据不支持资源。路径:MyApp \ Entity \ FOO - > Doctrine \ ORM \ PersistentCollection - > MyApp \ Entity \ Product - > Doctrine \ ORM \ PersistentCollection - > DoctrineORMModule \ Proxy__CG __ \ MyApp的\ MyApp的\品牌
显然,您无法序列化持久性集合。
我在谷歌上搜索了this与Symfony相关的问题。但是如何在独立的Serializer库中解决这个问题?
非常感谢。
修改
这与JMS注释有什么关系吗?我应该使用某些注释来使其正常工作吗?
答案 0 :(得分:1)
我猜这里的问题是PersistentCollection可能包含对数据库连接的引用,因此JMS无法处理资源类型。
如果你只想要第一级序列化,那么我想你可能会破解它:
foreach ($repo->findAll() as $found) {
// Set these to basically empty arrays
$found->setRelation1(new \Doctrine\Common\Collections\ArrayCollection);
$found->setRelation2(new \Doctrine\Common\Collections\ArrayCollection);
$data[] = $hydrator->extract($found);
}
或者您可以扩展JMS Serialize函数以忽略Resource集合而不是抛出异常。