我已经使用 Symfony 序列化程序来序列化我的 Recherche
目的。
在 Recherche
对象,我有子对象:Categorie
和 Lieu
.
当我反序列化我的 Recherche
对象,所有子对象都转换为数组。我希望它们再次成为对象。
这就是我序列化对象的方式:
$encoders = array(new JsonEncoder());
$normalizer = new ObjectNormalizer();
$normalizer->setIgnoredAttributes(array('parent', 'enfants'));
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getCode();
});
$normalizers = array($normalizer);
$serializer = new Serializer($normalizers, $encoders);
$rechercheJson= $serializer->serialize($recherche, 'json');
这就是我反序列化它的方式:
$encoders = array(new JsonEncoder());
$normalizer = new ObjectNormalizer();
$normalizer->setIgnoredAttributes(array('parent', 'enfants'));
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getCode();
});
$normalizers = array($normalizer);
$serializer = new Serializer($normalizers, $encoders);
$recherche = $serializer->deserialize($recherche_json, Recherche::class, 'json');
我认为可能与规范化器有关,但我在文档中找不到任何对我有帮助的内容。
任何人都有帮助的想法?
谢谢 !
编辑 :
看到这个帖子后:Denormalize nested structure in objects with symfony 2 serializer
我试过这个:
$encoders = array(new JsonEncoder());
$normalizer = new ObjectNormalizer(null, null, null, new SerializationPropertyTypeExtractor());
$normalizer->setIgnoredAttributes(array('parent', 'enfants'));
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getCode();
});
$normalizers = array($normalizer, new ArrayDenormalizer());
$serializer = new Serializer($normalizers, $encoders);
$recherche = $serializer->deserialize($recherche_json, Recherche::class, 'json');
和 SerializationPropertyTypeExtractor:
class SerializationPropertyTypeExtractor implements PropertyTypeExtractorInterface {
/**
* {@inheritdoc}
*/
public function getTypes($class, $property, array $context = array())
{
if (!is_a($class, Recherche::class, true)) {
return null;
}
if ('make' !== $property) {
return null;
}
if ('lieu' === $property)
{
return [new Type(Type::BUILTIN_TYPE_OBJECT, true, LieuRecherche::class)];
}
if ('categorie' === $property)
{
return [new Type(Type::BUILTIN_TYPE_OBJECT, true, Categorie::class)];
}
return null;
}
}
这很好用!
最佳答案
我遇到了类似的问题,并尝试使用自定义 PropertyTypeExtractor 解决该问题。
由于我有许多带有嵌套对象的实体,这感觉很麻烦,而且当嵌套对象再次嵌套对象时它也不起作用。
我使用 PhpDocExtractor 和 ReflectionExtractor 找到了一个更好的解决方案,它为您提取属性信息。
$encoder = [new JsonEncoder()];
$extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
$normalizer = [new ArrayDenormalizer(), new ObjectNormalizer(null, null, null, $extractor)];
$serializer = new Serializer($normalizer, $encoder);
$result = $serializer->deserialize($data,someEntity::class,'json');
这为我完成了所有工作。我希望这会帮助某人。
关于serialization - symfony 反序列化嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49778907/