Question

I'm attempting to follow the tutorial here and seem to be struggling with serialization. When I marshal an object, I get the following output:

<?xml version="1.0" encoding="UTF-8"?>
<WrapBean>com.lists.beans.ChildBean@2df36f51com.lists.beans.ChildBean@49114668</WrapBean>

I'm expecting something more like this:

<?xml version="1.0" encoding="UTF-8"?>
<WrapBean>
  <ChildBean>
    <first_name>[name]</first_name>
    <last_name>[name[</last_name>
    <age>[age]</age>
  </ChildBean>
  <ChildBean>
    ...
  </ChildBean>
</WrapBean>

This is my main method:

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

        ArrayList<ChildBean> children = new ArrayList<ChildBean>();
        ChildBean c1 = new ChildBean();
        c1.setFname("larry");
        c1.setLname("sanderson");
        c1.setAge("13");
        children.add(c1);

        ChildBean c2 = new ChildBean();
        c2.setFname("amber");
        c2.setLname("smith");
        c2.setAge("11");
        children.add(c2);     

        QName qName = new QName("WrapBean");
        WrapBean wrapper = new WrapBean(children);
        JAXBElement<WrapBean> jaxbElement = new JAXBElement<WrapBean>(qName, WrapBean.class, wrapper);
        marshaller.setProperty(JAXBMarshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(jaxbElement, System.out);
    }

I can post the bean classes, if needed, but there's only the setters and getters and the annotations necessary to get the element names right. Can anyone help me with what I'm missing?

EDIT: I also wanted to mention, the wrapper object is the exact same as the tutorial:

public class Wrapper<T> {

    private List<T> items;

    public Wrapper() {
        items = new ArrayList<T>();
    }

    public Wrapper(List<T> items) {
        this.items = items;
    }

    @XmlAnyElement(lax=true)
    public List<T> getItems() {
        return items;
    }

}
Was it helpful?

Solution

You need to make the JAXBContext aware of the items that will be in the collection.

JAXBContext context = JAXBContext.newInstance(WrapperBean.class, ChildBean.class);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top