Jaxb Unmarshal Example Annotation Bibliography

We know that JAXB(Java Architecture for XML Binding) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. JAXB mostly is used while implementing webservices or any other such client interface for an application where data needs to be transferred in XML format instead of HTML format which is default in case of visual client like web browsers.

A good example is facebook APIs. Facebook has exposed its services through some open endpoints in form of RESTful webservices where you hit a URL and post some parameters, and API return you the data in xml format. Now it is upto you, how you use that data.

In this post, I am giving an example of marshalling and unmarshalling of collection of objects. These collections in java can be of type : List and Set implementations e.g. ArrayList or HashSet.

Maven dependencies

To run JAXB examples, we need to add run time maven dependencies like below:

<dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.2.8-b01</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.2-promoted-b65</version> </dependency>

Model classes

I have created a model class “Employee.java” which has some common fields. I want to build code which could parse a set of employees. Please note that JAXB requires @XmlRootElement annotation on top most class which we are going to marshal or unmarshal. ArrayList class is part of collection framework and it does not have any JAXB annotations. So We need to have another class “Employees.java” which will represent the set of employees. Now in this class we can add any annotation we like.

Employee.java

@XmlRootElement(name = "employee") @XmlAccessorType (XmlAccessType.FIELD) public class Employee { private Integer id; private String firstName; private String lastName; private double income; //Getters and Setters }

Employees.java

import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "employees") @XmlAccessorType (XmlAccessType.FIELD) public class Employees { @XmlElement(name = "employee") private List<Employee> employees = null; public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } }

Marshalling example

Marshalling is “to convert the java object into xml representation”. In below example code, I am writing the list of employees first in console, and then in a file.

//Initialize the employees list static Employees employees = new Employees(); static { employees.setEmployees(new ArrayList<Employee>()); //Create two employees Employee emp1 = new Employee(); emp1.setId(1); emp1.setFirstName("Lokesh"); emp1.setLastName("Gupta"); emp1.setIncome(100.0); Employee emp2 = new Employee(); emp2.setId(2); emp2.setFirstName("John"); emp2.setLastName("Mclane"); emp2.setIncome(200.0); //Add the employees in list employees.getEmployees().add(emp1); employees.getEmployees().add(emp2); } private static void marshalingExample() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //Marshal the employees list in console jaxbMarshaller.marshal(employees, System.out); //Marshal the employees list in file jaxbMarshaller.marshal(employees, new File("c:/temp/employees.xml")); }

Output of above code is :

Unmarshalling example

Unmarshalling is the process of converting the xml back to java object. Let’s see the example of our Employees class.

private static void unMarshalingExample() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); //We had written this file in marshalling example Employees emps = (Employees) jaxbUnmarshaller.unmarshal( new File("c:/temp/employees.xml") ); for(Employee emp : emps.getEmployees()) { System.out.println(emp.getId()); System.out.println(emp.getFirstName()); } } Output: 1 Lokesh 2 John

Sourcecode Download

To download the sourcecode of above example follow below link.

Download sourcecode

Happy Learning !!


Java Architecture for XML Binding (JAXB) is a software framework that allows mapping Java classes to XML and back.

There are two important processes offered by the  JAXB  framework:

  • marshal – the process to convert a Java object into an XML file.
  • unmarshal – the process to convert XML content into a Java Object.

The following table describes the default data type bindings between the XML data types and Java data types.

XML Schema TypeJava Data Type

Class annotation

There are three annotations used:

  • XmlRootElement – this is added to the class and will map the class to the XML;
  • XmlElement – is used to methods or property and will map the property to an XML element.
  • XmlAttribute – is used to methods or property and will map the property to an XML attribute.

For this article will choose a simple User class to be marshaled and unmarshaled.

package com.admfactory.jaxb; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class User { private int id; private String name; private String address; private String email; public int getId() { return id; } @XmlAttribute public void setId(int id) { this.id = id; } public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public String getAddress() { return address; } @XmlElement public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } @XmlElement public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User [id:" + id + ",name: " + name + ", email:" + email + ", address: " + address + "]"; } }

Object to XML

To convert the object to XML the marshaller.marshal() method is used.

package com.admfactory.jaxb; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JAXBToXML { public static void main(String[] args) { System.out.println("JAXB Object to XML example"); System.out.println(); User user = new User(); user.setAddress("John Islip, London"); user.setEmail("[email protected]"); user.setId(33); user.setName("John Doe"); try { JAXBContext context = JAXBContext.newInstance(User.class); Marshaller marshaller = context.createMarshaller(); /** output the XML in pretty format */ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); /** display the output in the console */ marshaller.marshal(user, System.out); /** put the XML to the file - will be used by the unmarshal example */ marshaller.marshal(user, new File("user.xml")); } catch (JAXBException e) { e.printStackTrace(); } } }

Output

JAXB Object to XML example <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <user id="33"> <address>John Islip, London</address> <email>[email protected]</email> <name>John Doe</name> </user>

XML to Object

To convert the XML file to object the marshaller.unmarshal() method is used.

package com.admfactory.jaxb; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class JAXBToObject { public static void main(String[] args) { System.out.println("JAXB XML to Object example"); System.out.println(); try { JAXBContext context = JAXBContext.newInstance(User.class); Unmarshaller unmarshaller = context.createUnmarshaller(); User user = (User) unmarshaller.unmarshal(new File("user.xml")); System.out.println(user); } catch (JAXBException e) { e.printStackTrace(); } } }

Output

JAXB XML to Object example User [id:33,name: John Doe, email:[email protected], address: John Islip, London]

References

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *