XML > JAXB > Customize XML Tag names using Field Accessor
Customize XML Tag names using Field Accessor
The following example shows customizing XML tag name using @XmlElement annotation.
JAXB uses the following accessor types to serialize java object to XML,
PUBLIC_MEMBER (default) - Binds public getters/setters/fields
FIELD - Binds non static, non transient fields
PROPERTY - Binds public getters/setters
NONE - No binding
As the default accessor type is PUBLIC_MEMBER, the annotation(Such as @XmlElement) we put at
field level causes Class has two properties of the same name exception.
This is because JAXB tries to get data using both fields and getter/setter pairs.
We can solve this problem by placing annotation at field level by specifying FIELD accessor type.
@XmlRootElement(name = "student")
@XmlAccessorType(XmlAccessType.FIELD) //Allows to get data through fields rather than public getter/setters public class Student4 {
public static void main (String [] args) throws JAXBException {
Student4 student = new Student4("Sriram", "Kasireddi", 2, "Painting", new Date());
/**
* Create JAXB Context from the classes to be serialized
*/
JAXBContext context = JAXBContext.newInstance(Student4.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(student, System.out);