Domain Model
I will use the following domain model for this example. Note how there are no annotations of any kind.
Customer
Customer is the root object in this example. Normally we would annotate it with @XmlRootElement. Later in the demo code you will see how we can use an instance of JAXBElement instead.
package blog.defaults; import java.util.List; public class Customer { private String firstName; private String lastName; private List<PhoneNumber> phoneNumbers; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public List<PhoneNumber> getPhoneNumbers() { return phoneNumbers; } public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) { this.phoneNumbers = phoneNumbers; } }
PhoneNumber
I have purposefully given the fields in this class nonsense names, so that later when we look at the XML you will be able to see that by default the element names are derived from the properties and not the fields.
I have purposefully given the fields in this class nonsense names, so that later when we look at the XML you will be able to see that by default the element names are derived from the properties and not the fields.
package blog.defaults; public class PhoneNumber { private String foo; private String bar; public String getType() { return foo; } public void setType(String type) { this.foo = type; } public String getNumber() { return bar; } public void setNumber(String number) { this.bar = number; } }
Demo Code
Since we haven't used @XmlRootElement (or @XmlElementDecl) to associate a root element with our Customer class we will need to tell JAXB what class we want to unmarshal the XML document to. This is done by using one of the unmarshal methods that take a Class parameter (line 14). This will return a JAXBElement, the Customer object is then accessed by calling getValue on it (line 15). To marshal the object back to XML we need to ensure that it is wrapped in a JAXBElement to supply the root element information (line 17).
package blog.defaults; import javax.xml.bind.*; import javax.xml.namespace.QName; import javax.xml.transform.stream.StreamSource; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Customer.class); StreamSource xml = new StreamSource("src/blog/defaults/input.xml"); Unmarshaller unmarshaller = jc.createUnmarshaller(); JAXBElement<Customer> je1 = unmarshaller.unmarshal(xml, Customer.class); Customer customer = je1.getValue(); JAXBElement<Customer> je2 = new JAXBElement<Customer>(new QName("customer"), Customer.class, customer); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(je2, System.out); } }
input.xml/Output
The following is the input to and output from running the demo code. The first thing we see is that it is a very reasonable XML representation of the data, there aren't any JAXB artifacts. By default JAXB will marshal everything as XML elements, and based on our PhoneNumber class we see that the element names were derived from the property names.
<?xml version="1.0" encoding="UTF-8"?> <customer> <firstName>Jane</firstName> <lastName>Doe</lastName> <phoneNumbers> <number>555-1111</number> <type>work</type> </phoneNumbers> <phoneNumbers> <number>555-2222</number> <type>home</type> </phoneNumbers> </customer>
Further Reading
If you enjoyed this post then you may also be interested in:
- The majority of the articles on this blog describe how to leverage the power of JAXB's metadata to support different use cases, I invite you to check them out:
- If you are interested in specifying metadata without using annotations, you may be interested in EclipseLink JAXB (MOXy)'s external mapping document:
Since version 2.1 there is the utility class javax.xml.bind.JAXB that could help to shrink your Demo code.
ReplyDeleteThe javax.xml.bind.JAXB is fewer lines of code, but I don't use it because it doesn't optimize performance. Each time you use java.xml.bind.JAXB it recalculates the metadata. It is better do do this once by creating a thread safe instance of JAXBContext and then creating instance of Marshaller and Unmarshaller from that.
Delete-Blaise
what about attributes? is their any default behavior in JAXB for writing out attributes?
ReplyDeleteBy default all properties and public fields will map to XML elements. You can use the @XmlAttribute annotation to have a field/property map to an XML attribute instead.
Delete-Blaise
This is enormously helpful. Thanks for this and for your helpful response on stackoverflow.com. http://stackoverflow.com/questions/14338525/how-do-i-write-a-deep-xml-document-using-jaxb
ReplyDeleteThanks in advance!
ReplyDeleteOkay, but what if I want to override the default behavior of jaxb and not use annotations? (For example, let's say I have 3 different xml files I'm unmarshalling that all go to the same object, and they each call the same field name something different.)
ReplyDeleteYou could use the external mapping file extension in EclipseLink JAXB (MOXy):
Delete- Mapping Objects to Multiple XML Schemas - Weather Example
-Blaise
I forgot to read this line: "If you are interested in specifying metadata without using annotations, you may be interested in EclipseLink JAXB (MOXy)'s external mapping document" I guess I should learn to RTFA.
ReplyDelete