如何使用Symfony Serializer反序列化一系列复杂对象?

时间:2017-04-03 12:48:49

标签: php symfony serialization xml-deserialization

如何反序化此XML

<Outer>
   <simpleProperty1>A</simpleProperty1>
   <simpleProperty2>B</simpleProperty2>
   <Inner>
      <simpleProperty3>C</simpleProperty3>
      <simpleProperty4>D</simpleProperty4>
   </Inner>
   <Inner>
      <simpleProperty3>E</simpleProperty3>
      <simpleProperty4>F</simpleProperty4>
   </Inner>
</Outer>

进入一些PHP类:

class Outer 
{
   /** @var string */
   private $simpleProperty1;
   /** @var string */
   private $simpleProperty2;
   /** @var Inner[] */
   private $inners;

   [insert getters and setters here]
}

class Inner 
{
   /** @var string */
   private $simpleProperty3;
   /** @var string */
   private $simpleProperty4;

   [insert getters and setters here]
}

使用Symfony Serializer

外部对象及其简单属性被填充,但是我得到一个包含两个包含simpleProperty3simpleProperty4的关联数组的关联数组,而不是内部对象。

1 个答案:

答案 0 :(得分:1)

我能够使用自定义PropertyExtractor解决它,将序列化器指向正确的类型:

$encoders = [new XmlEncoder('response', LIBXML_NOERROR)];
$normalizers = [
    new ArrayDenormalizer(),
    new ObjectNormalizer(null, null, null, 
      new class implements PropertyTypeExtractorInterface
        {
          private $reflectionExtractor;

          public function __construct()
          {
              $this->reflectionExtractor = new ReflectionExtractor();
          }

          public function getTypes($class, $property, array $context = array())
          {
              if (is_a($class, Outer::class, true) && 'Inner' === $property) {
                return [
                  new Type(Type::BUILTIN_TYPE_OBJECT, true, Inner::class . "[]")
                ];
              }
              return $this->reflectionExtractor->getTypes($class, $property, $context);
          }
        })
    ];
$this->serializer = new Serializer($normalizers, $encoders);