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

如何使用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 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页