Nov 8, 2018

JAXB (Java Architecture for XML Binding) Annotations

@XmlRootElement

Define the root element for the XML to be produced with @XmlRootElement JAXB annotation. The name of the root XML element is derived from the class name.


@XmlRootElement
public class Example implements Serializable {
...
}


You can also specify the name of the root element of the XML using its name attribute, for example @XmlRootElement(name = "MyExample")

@XmlElement

Annotate all fields that needs to be included in XML/JSON output with @XMLElement.
@XmlElement
public String getEmail() { return email;
}
Either annotate all fields or all getter methods in your Entity bean. A mix of both is not supported. Add @XmlAccessorType(XmlAccessType.FIELD) at the class level if you want to annotate private fields instead of getter methods. By default JAXB impls will treat properties (get/set pairs), public fields (instance variables), and annotated non-public fields as mapped. If you just annotate a field you will get a duplicate mapped property exception. If you want to annotate the field you should specify @XmlAccessorType(XmlAccessType.FIELD) on the class.

@XmlType

Specify the order in which XML elements or JSON output will be produced.
@XmlRootElement
@XmlType(propOrder = { "id", "firstName", "lastName", "email" })public class Lead implements Serializable {
...
}
The above @XmlType annotation will produce the following XML.
<lead>
<id>88</id>
  <firstname>FirstName</firstname>
  <lastname>LastName</lastname>
  <email>su@i88.ca</email>
  <telephone>8888888888</telephone>
</lead>


Similarly, it will produce the following JSON.
{"id":"88","firstName":"FirstName","lastName":"LastName","email":"su@i88.ca","telephone":"8888888888"}


@XmlTransient
Annotate fields that we do not want to be included in XML or JSON output with @XMLTransient.
@XmlTransient
public Date getVersion() { return version;
}

@XmlSeeAlso

Use @XmlSeeAlso annotation when we want another Entity bean included in the XML output. In our example below, Leads bean refers to Lead bean and the XML output should include XML generated from Lead Entity too.
@XmlRootElement(name = "Leads")@XmlSeeAlso(Lead.class)public class Leads { @XmlElement(name = "leads") public List<Lead> getLeads() {   return leads; }
...
}


To include more than 1 classes, we can use @XmlSeeAlso JAXB annotation as:

@XmlSeeAlso({ A.class, B.class })