Spring引导使用列表列表对xml进行解组失败



我已经被这个问题困扰了一个多星期了,我正试图将Spring Boot端点的@RequestBody中的application/xml解组为POJO。每个foo中的条列表无法解组,foo.bars变为null。如果我将Foo中的List of Bars字段更改为一个Bar,我将获得每个Foo的最后一个Bar。但是,Bar实例无法对XmlValue Bar.value进行解组。b和Foo的顺序都被正确地解组。

我有一个像这样的xml:

<a>
<b>1</b>
<c>
<foo order="1">
<bar order="11">1</bar>
<bar order="22">2</bar>
<bar order="33">3</bar>
</foo>
<foo order="2">
<bar order="44">4</bar>
<bar order="55">5</bar>
<bar order="66">6</bar>
</foo>
</c>
</a>

以及以下POJO来分解它们:

Bar.java

@XmlAccessorType(XmlAccessType.FIELD)
public class Bar {

@XmlAttribute(name = "order")
Integer number;

@XmlValue
Integer value;

public Bar() {}

public Bar(int number, int value){
this.number = number;
this.value = value;
}

public Integer getNumber() {
return number;
}

public void setNumber(Integer number) {
this.number = number;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}
}

Foo.java

public class Foo {
@XmlAttribute(name = "order")
Integer order;

@XmlElement(name = "bar")
List<Bar> bars;

public Foo() {}

public Foo(int order, List<Bar> bars){
this.order = order;
this.bars = bars;
}

public Integer getOrder() {
return order;
}

public void setOrder(Integer order) {
this.order = order;
}

public List<Bar> getBars() {
return bars;
}

public void setBars(List<Bar> bars) {
this.bars = bars;
}

}

Body.java

@XmlRootElement(name = "a")
@XmlAccessorType(XmlAccessType.FIELD)
public class Body {
Integer b;
List<Foo> c;
public Body(){
}
public Body(int b, List<Foo> c){
this.b = b;
this.c = c;
}
public Integer getB() {
return b;
}
public void setB(Integer b) {
this.b = b;
}
public List<Foo> getC() {
return c;
}
public void setC(List<Foo> c) {
this.c = c;
}
}

我的终点:

public Response postData(@RequestBody Body body) {
...

感谢您的帮助。

<a>元素中<c><foo>XML元素的结构与Body类中的Java代码不匹配:

List<Foo> c;

有两种替代方法可以解决这个问题。

第一种选择(直接方式(:
Body类中,您将上面的行替换为

C c;

(当然,还要相应地更改构造函数、getter和setter(。此外,您需要创建另一个Java类C

@XmlAccessorType(XmlAccessType.FIELD)
public class C {
@XmlElement(name = "foo")
List<Foo> foos;
// constructor, getter, setter (omitted here for brevity)
}

或者第二种选择(比上面的要简单得多,因为您不需要更改类结构(:
Body类中,您用替换代码行

@XmlElementWrapper(name = "c")
@XmlElement(name = "foo")
List<Foo> c;

最新更新