【发布时间】:2018-09-21 13:33:54
【问题描述】:
我已经使用 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;
}
}
这很好用!
【问题讨论】:
-
我通常将策略模式与 symfony 的序列化程序组件一起使用。它允许您准确定义规范化和非规范化对象/数组的外观。稍后我会发送一个示例。
-
是的,一个例子可能很好,因为我不明白:-)
标签: serialization deserialization symfony-3.4