为什么在此示例中,bazes列表未正确解组?示例结果是Baz
中具有null属性的单个ArrayList
。如何让它正常工作?
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
答案 0 :(得分:1)
您需要使用@XmlElementWrapper
指定包装器对象,类似
@XmlElementWrapper(name = "bazes")
@XmlElement(name = "baz", type = Baz.class)
public ArrayList<Baz> bazes;