已检测到循环引用(配置限制:1)Serializer SYMFONY

时间:2016-05-17 09:19:23

标签: json serialization symfony

您好我的项目Symfony我想将我的实体转换为数组Json所以我选择序列化器来实现这一点,而且我也想忽略一些属性因为转换太长了所以我读了Symfony文档 http://symfony.com/doc/current/components/serializer.html#ignoring-attributes 我复制这段代码

 $flowsites =    $this->getDoctrine()->getRepository("QSCORBundle:Flow_Site")->findAll();
 $normalizer = new ObjectNormalizer();
 $normalizer->setIgnoredAttributes(array('company')); 
 $encoder = new JsonEncoder();

 $serializer = new Serializer(array($normalizer), array($encoder));
 $flow_sites = $serializer->serialize($flow_sites, 'json');

 var_dump( $flow_sites );
 die();

此后错误生成 检测到循环引用(配置限制:1) 所以为了解决这个问题,我对我的代码进行了一些更改

$normalizer = new ObjectNormalizer(null);
$normalizer->setIgnoredAttributes(array('company', 'origin'));
$normalizer->setCircularReferenceHandler(function ($object) {
    return $object->getId();
});
$encoder = new JsonEncoder();
//$serializer = $this->get('serializer');
$serializer = new Serializer(array($normalizer), array($encoder));

$flowsites = $this->getDoctrine()->getRepository("QSCORBundle:Flow_Site")->findAll();
$jsonflowsites =  $serializer->serialize( $flowsites, 'json');
var_dump( $jsonflowsites );
die();

0 个答案:

没有答案