我有这样的xml
<TopLevel attr1="foo">
<Midlevel attr2="bar">
<BottomLevel>
<data1>blahblah</data1>
<data2>blahblah</data2>
</BottomLevel>
...more bottom level elements...
</Midlevel>
...moreMidLevelElements...
</TopLevel>
现在,我知道@JsonUnwrapped注释可以帮助一个级别(在所有示例中均显示)。但是,当我尝试反序列化捕获外部图层属性的BottomLevel对象时,我只是为所有内容获取了空值。
谁能帮我展平这个xml?我试图概括这个问题。理想情况下,最终结果将是List
我的pojo有田野 数据1 数据2 attr1 attr2
答案 0 :(得分:1)
不要以为这是对这个问题的完美答案,但是它可以帮助解决您遇到的问题。 (以一种骇人听闻的方式)
public static void main(String[] args) throws IOException {
String xml = "<TopLevel attr1=\"foo\">\n" +
" <Midlevel attr2=\"bar\">\n" +
" <BottomLevel>\n" +
" <data1>blahblah</data1>\n" +
" <data2>blahblah</data2>\n" +
" </BottomLevel>\n" +
" </Midlevel>\n" +
" <Midlevel attr2=\"bar2\">\n" +
" <BottomLevel>\n" +
" <data1>blahblah2</data1>\n" +
" <data2>blahblah2</data2>\n" +
" </BottomLevel>\n" +
" </Midlevel>\n" +
"</TopLevel>";
ObjectMapper xmlMapper = new XmlMapper();
System.out.println(xmlMapper.readValue(xml, TopLevel.class)); //Once here, you can now do custom mapping with the TopLevel class object to your custom POJO
}
@JsonIgnoreProperties(ignoreUnknown = true)
static class TopLevel {
@JacksonXmlProperty(isAttribute = true)
private String attr1;
@JacksonXmlElementWrapper(localName = "Midlevel", useWrapping = false)
@JacksonXmlProperty(localName = "Midlevel")
private List<MidLevel> midLevel = new ArrayList<>();
@Override
public String toString() {
return "TopLevel{" +
"attr1='" + attr1 + '\'' +
", midLevel=" + midLevel +
'}';
}
}
static class MidLevel {
@JacksonXmlProperty(isAttribute = true)
private String attr2;
@JacksonXmlElementWrapper(localName = "BottomLevel", useWrapping = false)
@JacksonXmlProperty(localName = "BottomLevel")
private List<BottomLevel> bottomLevels = new ArrayList<>();
@Override
public String toString() {
return "MidLevel{" +
"attr2='" + attr2 + '\'' +
", bottomLevels=" + bottomLevels +
'}';
}
}
static class BottomLevel {
@JacksonXmlProperty(localName = "data1")
private String data1;
@JacksonXmlProperty(localName = "data2")
private String data2;
@Override
public String toString() {
return "BottomLevel{" +
"data1='" + data1 + '\'' +
", data2='" + data2 + '\'' +
'}';
}
}