为什么在此示例中,bazes 列表未正确解码?示例导致 ArrayList
中的单个 Baz
具有 null 属性。如何使其正常工作?
public class Application {
private final static String FOO_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><FooBar><foo>foo</foo><bar>1</bar>"
+ "<bazes><baz><baz1>baz11</baz1><baz2>baz12</baz2></baz><baz><baz1>baz21</baz1><baz2>baz22</baz2></baz></bazes>"
+ "</FooBar>";
public static void main(String[] args) throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(FooBar.class);
Unmarshaller u = ctx.createUnmarshaller();
FooBar result = (FooBar) u.unmarshal(new ByteArrayInputStream(FOO_XML.getBytes()));
System.out.println(result);
System.out.println(result.bazes.size());
}
@XmlRootElement(name = "FooBar")
@XmlAccessorType(XmlAccessType.FIELD)
public static class FooBar {
@XmlElement
private String foo;
@XmlElement
private int bar;
@XmlElement(name = "bazes")
public ArrayList<Baz> bazes;
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(foo + " ");
sb.append(bar + " ");
for (Baz baz : bazes) {
sb.append(baz.baz1 + " " + baz.baz2 + " ");
}
return sb.toString();
}
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public static class Baz {
@XmlElement
private String baz1;
@XmlElement
private String baz2;
}
}
}
结果如下
foo 1 null null
1
最佳答案
您需要使用 @XmlElementWrapper
和类似的内容指定包装器对象
@XmlElementWrapper(name = "bazes")
@XmlElement(name = "baz", type = Baz.class)
public ArrayList<Baz> bazes;
关于java - jaxb 解码列表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42482761/