dpw43061 2017-04-03 12:48
浏览 170
已采纳

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

how can I deserialize this 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>

into some PHP classes:

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

using the Symfony Serializer?

The outer object and its simple properties are filled, but instead of the inner object I get an associative array containing two more associative arrays that contain the simpleProperty3 and simpleProperty4.

  • 写回答

1条回答 默认 最新

  • douyou2234 2017-04-03 13:40
    关注

    I was able to solve it with a custom PropertyExtractor that points the serializer to the correct type:

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突