December 20, 2013

JAXB automatically will NOT marshal fields with non-public getter/setter pairs

Recently I have been investigating why JAXB does not marshal one of the classes in the application I was working on. This class had its setters marked as protected, while all the other classes had public setters. As it has turned out this discrepancy was responsible for the issue.

JAXB by default marshals only fields that have a corresponding setter/getter pair marked as public.

So when you want to marshal such class:
@XmlRootElement
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer id;
    private String name;
 
    public Integer getId() {
        return id;
    }
    protected void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    protected void setName(String name) {
        this.name = name;
    } 
}
you have to append the following annotation:
@XmlAccessorType(XmlAccessType.FIELD)

No comments:

Post a Comment