Marshalling and Unmarshalling in Java using JAXB

In this tutorial, we will learn about Marshalling and Unmarshalling in Java using JAXB.

How to convert an object into XML and XML back to object in Java ?

JAXB provides a mechanism to convert an object into XML, this process is called as Marshalling and the reverse process of converting an XML back to Java object is called as Unmarshalling. 

JAXB provides annotations to do the marshalling and unmarshalling.

Let’s see Marshalling and Unmarshalling with an example using JAXB.

Marshalling using JAXB:

Create a Car.java object which needs to be marshalled so that an XML will be generated.

Car.java:

Let’s create a MarshallingDemo.java class to check the result.

MarshallingDemo.java:

Let’s run the demo class and see the result.

Output:

If you check the output, the Car.java object is now converted to XML. The elements in the Car root element are in the order that is been provided in the propOrder list of @XmlType annotation.

How to exclude few fields from the XML ?

There can be a requirement to exclude few of the fields from the object in the generated XML.

To excluded fields, just annotate that field with @XmlTransient. Let’s see this with an example.

Create MyCar.java class. Here we are annotating model field with @XmlTransient.

MyCar.java:

Let’s crate the demo class to check the result.

MarshallingDemo1.java:

Let’s run the demo class and see the output.

Output:

If you observe the output, the field model which is annotated with @XmlTransient is excluded from the XML.

We have marshalled a Car.java object to XML. Let’s see Unmarshalling of XML with an example.

Unmarshalling using JAXB:

Create Car.xml to unmarshal it.

Car.xml:

Create the UnmarshallingDemo.java class to check the result.

UnmarshallingDemo.java:

Let’s run the demo class and check the result.

Output:

If you observe the output, Car.xml is now converted back to Car.java object.

Related posts

Leave a Comment