JAXB – Marshal and Unmarshal List or Set of Objects

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 to marshal and unmarshal the collection of objects. These collections in java can be of type : List and Set implementations e.g. ArrayList or HashSet.

1) JAXB 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>

2) Model Classes

I have created a model class “Employee” 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” which will represent the set of employees. Now in this class we can add any annotation we like.

@XmlRootElement(name = "employee")
@XmlAccessorType (XmlAccessType.FIELD)
public class Employee 
{
	private Integer id;
	private String firstName;
	private String lastName;
	private double income;
	
	//Getters and Setters
}
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;
	}
}

3) Marshal List to XML 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 :

JAXB marshalling example output
JAXB marshalling example output

4) Unmarshal XML to List Example

Unmarshalling is the process to convert 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

5_ Sourcecode Download

To download the sourcecode of above example follow below link.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

44 thoughts on “JAXB – Marshal and Unmarshal List or Set of Objects”

  1. I have this exact problem but with the addition of this data being inside another root object which I can’t get to work.
    Put your employees inside tags. How to you make a class called Company that will unMarshall the employees? I have success with the pattern that you gave, but this one last step returns null no matter how I try?

    Reply
  2. Hello,
    I am Creating three pojo classess(Details,Subscriber,Publisher).In Details class i am 2 creating list of subscriber type and publisher type.in Main Method i am creating their instance and adding in a list.But i am getting all the elements from each list together.But what i want is first element from subscriber and then publisher and then again 2nd element from subscriber and then publisher.Below are my Actual output and Expected Output

    Actual Output
    ---------------------------------
    <Details>
      <Subscriber>
       <firstName></firstName>
       <Address></Adddress>
       <Mobile></Mobile>
      </Subscriber>
      <Subscriber>
       <firstName></firstName>
       <Address></Adddress>
       <Mobile></Mobile>
      </Subscriber>
      <Publisher>
       <BookName></BookName>
       <Price></Price>
      </Publisher>
      <Publisher>
       <BookName></BookName>
       <Price></Price>
      </Publisher>
    </Details>
    
    
    Expected Output
    ------------------------------
    <Details>
      <Subscriber>
       <firstName></firstName>
       <Address></Adddress>
       <Mobile></Mobile>
      </Subscriber>
      <Publisher>
       <BookName></BookName>
       <Price></Price>
      </Publisher>
      <Subscriber>
       <firstName></firstName>
       <Address></Adddress>
       <Mobile></Mobile>
      </Subscriber>
      <Publisher>
       <BookName></BookName>
       <Price></Price>
       </Publisher>
    </Details>
    
    
    Reply
  3. This example is what I needed to build a xml file from an object. I was fighting with the ArrayList of objects setter for two evenings.

    Thanks a lot

    Reply
  4. Hi Lokesh,
    Nice example. But i didn’t got one thing. If we want to display the id of the first employee only and nothing else Then how will you do it. Because here all the contents stored in the list is being displayed. If I want a single data stored in the List then how will i get it.

    Reply
  5. Hi Lokesh, Nice content. i need clarity. To convert java object to xml representation, we need have to JAXB.
    Without JAXB is it possible? I am using spring restservices with JAXB.

    Reply
  6. When unmarshalling, is there a way to convert List types i.e. where

    <xs:element maxOccurs="unbounded" minOccurs="0" name="errorDataList" nillable="true" type="ErrorData"/>

    , into Arrays i.e.

    protected ErrorData[] errorDataList;

    instead of

    protected List<ErrorData> errorDataList

    .

    I think it can be achieved by using a bindings file but I am not aware of the exact configuration to put in this file. Can you help?

    Reply
  7. Hi, how can I run this without maven? I downloaded the three source files and try to compile and run with javac and java, it compiled ok, but got “could not find or load main class TestEmployeeMarshing” error when running. I used the same thing in STS and it worked fine? Can you help me? Thank you.

    Reply
  8. I want to have the Employees class to be a property of the Department class, so that the root node is the Department and the XML looks like:

    How should I annotate the Department, The Employees, and the Employee classes to generate such an XML?

    Reply
  9. Can any one help me in detail how to extract the records from the belwo XML snippet

    12
    PRASAD56
    Chennai
    2014-10-20T00:00:00+05:30
    pkk@gmail.co.in
    2014-08-01T00:00:00+05:30
    BSM_RESTeter
    9916347942
    9916347942
    944990031
    22

    3
    prasadk
    10007896

    18
    PRASAD61
    Chennai
    2014-10-24T00:00:00+05:30
    pkk@gmail.co.in
    2014-08-01T00:00:00+05:30
    BSM_RESTeter
    9916347942
    9916347942
    9916347942
    23

    prasadk
    10007896

    1
    1
    2
    12

    Reply
          • Hi Lokesh ,Below is my XML snippet.Please suggest a best way to extract the two records

            
            <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
            <collection xmlns:sure="http://www.proj1.com/sure" xmlns:atom="http://www.w3.org/2005/Atom">
            <links/>
            <element xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="sure:customer">
            <atom:link rel="customer" href="http://172.19.112.145:8080/proj1/sure/customerFeatures/3/customer"/>
            <atom:link rel="self" href="http://172.19.112.145:8080/Proj1/sure/customerFeatures/3"/><atom:link rel="state" href="http://172.19.112.145:8080/Proj1/sure/customers/12/state"/>
            <atom:link rel="customerFeatures" href="http://172.19.112.145:8080/Proj1/sure/customers/12/customerFeatures"/>
            <atom:link rel="customerFeatures" href="http://172.19.112.145:8080/Proj1/sure/customers/12/customerFeatures"/>
            <atom:link rel="ipPool" href="http://172.19.112.145:8080/Proj1/sure/customers/12/ipPool"/>
            <atom:link rel="status" href="http://172.19.112.145:8080/Proj1/sure/customers/12/status"/>
            <atom:link rel="paths" href="http://172.19.112.145:8080/Proj1/sure/customers/12/paths"/>
            <sure:customerId>12</sure:customerId>
            <sure:customerName>PRASAD56</sure:customerName>
            <sure:address>Chennai</sure:address>
            <sure:creationDate>2014-10-20T00:00:00+05:30</sure:creationDate>
            <sure:email>pkk@gmail.co.in</sure:email>
            <sure:lastUpdate>2014-08-01T00:00:00+05:30</sure:lastUpdate>
            <sure:nameDetail>BSM_RESTeter</sure:nameDetail>
            <sure:phoneBiz>9916347942</sure:phoneBiz>
            <sure:phoneHome>9916347942</sure:phoneHome>
            <sure:phoneMobile>944990031</sure:phoneMobile>
            <sure:rating>22</sure:rating>
            <sure:customerFeature>
            <atom:link rel="customer" href="http://172.19.112.145:8080/Proj1/sure/customerFeatures/3/customer"/>
            <atom:link rel="self" href="http://172.19.112.145:8080/Proj1/sure/customerFeatures/3"/>
            <sure:customerFeatureId>3</sure:customerFeatureId>
            <sure:name>prasadk</sure:name>
            <sure:value>10007896</sure:value>
            </sure:customerFeature>
            </element>
            
            <element xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="sure:customer">
            <atom:link rel="services" href="http://172.19.112.145:8080/Proj1/sure/customers/18/services"/>
            <atom:link rel="self" href="http://172.19.112.145:8080/Proj1/sure/customers/18"/>
            <atom:link rel="state" href="http://172.19.112.145:8080/Proj1/sure/customers/18/state"/>
            <atom:link rel="customerFeatures" href="http://172.19.112.145:8080/Proj1/sure/customers/18/customerFeatures"/>
            <atom:link rel="customerFeatures" href="http://172.19.112.145:8080/Proj1/sure/customers/18/customerFeatures"/>
            <atom:link rel="ipPool" href="http://172.19.112.145:8080/Proj1/sure/customers/18/ipPool"/>
            <atom:link rel="status" href="http://172.19.112.145:8080/Proj1/sure/customers/18/status"/>
            <atom:link rel="paths" href="http://172.19.112.145:8080/Proj1/sure/customers/18/paths"/>
            <sure:customerId>18</sure:customerId>
            <sure:customerName>PRASAD61</sure:customerName>
            <sure:address>Chennai</sure:address>
            <sure:creationDate>2014-10-24T00:00:00+05:30</sure:creationDate>
            <sure:email>pkk@gmail.co.in</sure:email>
            <sure:lastUpdate>2014-08-01T00:00:00+05:30</sure:lastUpdate>
            <sure:nameDetail>BSM_RESTeter</sure:nameDetail>
            <sure:phoneBiz>9916347942</sure:phoneBiz>
            <sure:phoneHome>9916347942</sure:phoneHome>
            <sure:phoneMobile>9916347942</sure:phoneMobile>
            <sure:rating>23</sure:rating>
            <sure:customerFeature>
            <atom:link rel="customer" href="http://172.19.112.145:8080/Proj1/sure/customerFeatures/9/customer"/>
            <atom:link rel="self" href="http://172.19.112.145:8080/Proj1/sure/customerFeatures/9"/>
            <sure:customerFeatureId></sure:customerFeatureId>
            <sure:name>prasadk</sure:name>
            <sure:value>10007896</sure:value>
            </sure:customerFeature>
            </element>
            
             <metaData>
            <totalPages>1</totalPages>
            <currentPage>1</currentPage>
            <totalElements>2</totalElements>
            <limit>12</limit>
            </metaData>
            
            </collection>
            
  10. There’s an existing program, where marshalling is included already. The problem is to unmarshal it. Whatever I try, it is not possible to unmarshal it. Can i send you a mail or something describing the problem?

    Reply
  11. Hi. I have got some java files from an xsd file using jaxb xcj command line..now i have to convert them to an xml file..i came to know that using schemagen of jaxb it can be done..i tried but it is giving me an xsd file..what i want is xml equivalent of all those java files plz reply asap..

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.