2017-04-03 103 views
0

我怎麼可以反序列化這個XML如何使用Symfony序列化器反序列化複雜對象的數組?

<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類:使用Symfony Serializer

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] 
} 

外部對象及其簡單屬性被填充,但取代內部對象,我得到一個包含兩個關聯數組的關聯數組,其中包含simpleProperty3simpleProperty4

+0

你可以看看[這裏](http://thomas.jarrand.fr/blog/serialization /),你可能需要定義一個自定義的denormalizer函數。 你也可以看看[這個問題](http://stackoverflow.com/questions/40033732/denormalize-nested-structure-in-objects-with-symfony-2-serializer) – segFault

+0

你可以生成一個像上面的XML 'Symfony Serializer'?那麼你也可以'反序列化'它再次。目前的文件,只有平坦/簡單的物體。你只能在INNER的getter/setter中注入一些東西,並將這些值綁定到manualy。但更好地深入@segFault顯示的鏈接 – JustOnUnderMillions

+0

@JustOnUnderMillions我可以序列化,但我仍然不能反序列化 –

回答

0

我能夠與指向串行正確類型的定製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);