Question

I have a class that I want to marshall and this class is annotated with @XmlRootElement. When I marshall an instance of it, JAXB creates an XML with nothing in it except the root element. When I manually annotate each field of my class then all fields are included. It seems like you have to annotate each field in order for it to be included in the output. Can somebody confirm this? If so, why is JAXB then is said to be configuration-by-exception when you have to configure each field?

Does not work:

@XmlRootElement
public class Person {
    private int name;
    private String email;
    private String tel;
    //constructor getters/setters
}

Produces <?xml version="1.0" encoding="UTF-8" standalone="yes"?><person/>.

The example below includes all the fields in the output.

@XmlRootElement
public class Person {
    @XmlElement private int name;
    @XmlElement private String email;
    @XmlElement private String tel;
    //constructor getters/setters
}
Was it helpful?

Solution

JAXB (JSR-222) implementations don't require any annotations at all:

I suspect there is something wrong with your getter/setter pairs. You need to make sure they are like the following:

public int getName() {
    return name;
}

public void setName(int name) {
    this.name = name;
}

UPDATE

I was apparently a victim of late night coding. When generating getters/setters I only chose getters and that JAXB did not like at all.

By default JAXB won't treat properties with only a getter as mapped. With only a getter you need to annotate with @XmlElement.

@XmlElement
public int getName() {
    return name;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top