生成包含列表的对象列表的XML

时间:2017-01-23 21:22:37

标签: java xml jaxb

我有一个对象结构,其中我有一个Layer1元素列表,这个Layer1包含一个Layer2参数列表,如下所示(getter,setters,ommited方法):

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
    @XmlElement(name = "layer1")
    private List<Layer1> layer1 = new ArrayList<>();
}

@XmlRootElement(name = "layer1")
@XmlAccessorType(XmlAccessType.FIELD)
public class Layer1 {

   @XmlElement(name = "layer2")
   private List<String> layer2;
}

我试图以这种方式将其编组为XML:

public void marshall(){
try {
   JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
   Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
   jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
   jaxbMarshaller.marshal(root.getlayer1(), System.out);
}

但是它不起作用并产生例外:

javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:567)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:467)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:308)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:236)

我想要低于输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <layer1>
        <layer2>value1</layer2>
        <layer2>value12</layer2>
        <layer2>value13</layer2>
    </layer1>
    <layer1>
        <layer2>value123</layer2>
        <layer2>value1231</layer2>
    </layer1>
    <layer1>
        <layer2>value12</layer2>
        <layer2>value1</layer2>
     </layer1>
</root>

请给我一些建议如何注释我的案例。我正在阅读其他类似的主题,但我仍然无法做出正确的解决方案。

0 个答案:

没有答案