可以FasterXML Jackson映射混合列表子元素

时间:2018-04-09 10:33:01

标签: jackson fasterxml jackson-dataformat-xml

使用FasterXML Jackson的对象映射器功能,我想解析这个XML片段:

<?xml version="1.0" encoding="utf-8"?>
<categories>
  <category name="A">
    <category name="B">
      <setting type="Float">
        <name>Bar</name>
      </setting>
    </category>
    <setting type="Float">
      <name>Foo</name>
    </setting>
    <category name="C">
      <setting type="Float">
        <name>Baz</name>
      </setting>
    </category>
  </category>
</categories>

使用以下Scala代码:

case class Categories(@JacksonXmlProperty(localName = "category") categories: List[Category])
case class Category(name: String, @JacksonXmlProperty(localName = "category") categories: List[Category], @JacksonXmlProperty(localName = "setting") settings: List[Setting])
case class Setting(`type`: String, name: String)

val xmlMapper = new XmlMapper()
xmlMapper.registerModule(DefaultScalaModule)
xmlMapper.setDefaultUseWrapper(false)

val categories = xmlMapper.readValue(snippet, classOf[Categories])
println(categories)
// Categories(List(Category(A,List(Category(C,null,List(Setting(Float,Baz)))),List(Setting(Float,Foo)))))

我可以看到结果中缺少B类。如果我更改了订单并在类别后移动setting,则按预期工作。

// Categories(List(Category(A,List(Category(B,null,List(Setting(Float,Bar))), Category(C,null,List(Setting(Float,Baz)))),List(Setting(Float,Foo)))))

<?xml version="1.0" encoding="utf-8"?>
<categories>
  <category name="A">
    <category name="B">
      <setting type="Float">
        <name>Bar</name>
      </setting>
    </category>
    <category name="C">
      <setting type="Float">
        <name>Baz</name>
      </setting>
    </category>
    <setting type="Float">
      <name>Foo</name>
    </setting>
  </category>
</categories>

所以如果将子列表混合在一起,它似乎是跳过元素。我可以在Mapper上设置一个属性来解决这个问题吗?

0 个答案:

没有答案