简体   繁体   中英

Empty List Unmarshall Java Object

I am trying to generate an XML document into a Java object using the JAXB Unmarshaller. in the XML document if there are elements to be presented to class Java object of class List, but the resulting object List is empty, although there is content in the it element,

Whether the element in the XML document because that is not as complete as the class presentation on Java, makes JAXB can not be parsing the XML document to Class representation?

Is there anyone that can help me, why it happened, and what's the solution?

Without knowing your object model or XML document it is difficult to tell why the unmarshal operation is not working properly. Below I have an example with a wrapped and unwrapped collection that may help you figure out what might be wrong in your use case:

input.xml/Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <item>A</item>
    <item>B</item>
    <item>C</item>
    <items>
        <item>D</item>
        <item>E</item>
        <item>F</item>
    </items>
</root>

Root

For the wrapped collection we will use the @XmlElementWrapper annotation to specify the wrapper element.

package forum11219454;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class Root {

    private List<String> list;
    private List<String> nestedList;

    @XmlElement(name="item")
    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    @XmlElementWrapper(name="items")
    @XmlElement(name="item")
    public List<String> getNestedList() {
        return nestedList;
    }

    public void setNestedList(List<String> nestedList) {
        this.nestedList = nestedList;
    }

}

Demo

package forum11219454;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11219454/input.xml");
        Root root = (Root) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

For More Information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM