HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / JAXB / JAXB – Marshal and Unmarshal List or Set of Objects

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.

Download Sourcecode

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Karen Jean Kramer

    September 26, 2019

    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?

  2. Harsh

    June 14, 2017

    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>
    
    
    • Lokesh Gupta

      June 15, 2017

      Interesting issue. I will try this in free time.

  3. Svetoslav

    March 9, 2017

    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

  4. Saumya

    July 20, 2016

    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.

    • Lokesh Gupta

      July 20, 2016

      Then probably, you should be using xpath. JAXB will not be a good solution in this particular case.

  5. Uma Maheswara Rao Marripudi

    March 30, 2016

    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.

    • Lokesh Gupta

      March 30, 2016

      No, JAXB is not required. You can use MOXy as well. Idea is that you need to use some interface which is capable of marshaling and unmarshalling.
      OR, you can directly build your XML object and send in response.

      I have one such example for JSON here: https://howtodoinjava.com/jersey/jax-rs-jersey-moxy-json-example/

      You can use it for building XML by using https://jersey.github.io/

      • Uma Maheswara Rao Marripudi

        March 31, 2016

        So to convert java object to xml or json format we need other interfaces like JAXB or Jackson.
        Other wise we can directly send our java object in the form of xml or json form as our wish.
        Mostly we use JAXB and Jackson , am I correct Lokesh?
        I have some confusion in web services while doing conversions like this. That’s why I am asking.

        • Lokesh Gupta

          March 31, 2016

          You are right.

  6. Hemlata

    March 18, 2016

    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?

    • Devender Singh

      January 7, 2019

      Hi Hemlata,

      Did you get any solution for this Problem? Please revert if you had this sorted.

  7. Jennifer

    January 18, 2016

    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.

    • Lokesh Gupta

      January 19, 2016

      Add class files path in classpath parameter.

  8. Zakaria

    July 23, 2015

    thank u for the article, didnt u forget to annotate the employee attributes with @XmlElement
    id, firstName etc ?

    • Lokesh Gupta

      July 23, 2015

      When you use @XmlAccessorType (XmlAccessType.FIELD) at class, then @XmlElement becomes optional.

  9. Javad

    May 3, 2015

    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?

  10. Himtie Liang

    March 20, 2015

    Many thanks! It really helps my work.

  11. Rajat

    January 23, 2015

    Hi ,
    I want to add a tostring method in the autogenerated class how can i do this

    • Lokesh Gupta

      January 23, 2015

      How you are generating the class? This SA thread has good information. Let me know if something else you want to know?

  12. PShukla

    December 10, 2014

    Thanks and it is a good basic tutorial !! 🙂

  13. praveen

    October 25, 2014

    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

    • Lokesh Gupta

      October 25, 2014

      Please read the message above in red to correctly post the code.

      • praveen

        October 25, 2014

        Hi lokesh ,I do not see any message in red

        • Lokesh Gupta

          October 25, 2014

          In comment box, please put your code inside [java] … [/java] OR [xml] … [/xml] tags otherwise it may not appear as intended. Tags are in small letters.

          • praveen

            October 25, 2014

            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>
            
            • Lokesh Gupta

              October 25, 2014

              Use jaxb with namespaces. An example could be: http://wiki.eclipse.org/EclipseLink/Release/2.4.0/JAXB_RI_Extensions/Namespace_Prefix_Mapper
              You need to google more for this.

  14. Ben

    September 29, 2014

    But in the unmarshalling example, you never defined getID() and getFirstName() so how would this work?

    • Lokesh Gupta

      September 29, 2014

      You see that I have written “//Getters and Setters”. Basically, I didn’t included them in example code here just to reduce the length of page.

  15. shan

    July 26, 2014

    how to migrate my jaxb 1.0 classes to 2.0

  16. Frostbite

    July 21, 2014

    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?

    • Lokesh Gupta

      July 21, 2014

      Can you please elaborate more your problem. Please provide some error logs OR code in which you are facing the error.

  17. Timothy

    June 4, 2014

    Suppose i have a list of employees withouth the wrapper tags i.e

    …

    …

    How do i unmarshall it to a list/set ?

    • Lokesh Gupta

      June 4, 2014

      Please paste the code inside [ java] ... [/java] OR [ xml] ... [/xml] tags.

      • Timothy

        June 4, 2014

        &lt;employee&gt;
        	&lt;a/&gt;
        	&lt;b/&gt;
        &lt;/employee&gt;
        &lt;employee&gt;
        	&lt;a/&gt;
        	&lt;b/&gt;
        &lt;/employee&gt;
        

        Note i don’t have the outer employees tag

        • Lokesh Gupta

          June 4, 2014

          You must have any root element in XML. In above xml snippet, there is no root element.

  18. Cesar

    April 10, 2014

    It’s great, thank you!

  19. DK

    March 31, 2014

    thanks, very helpful example.

  20. naveen

    March 6, 2014

    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..

    • Lokesh Gupta

      March 6, 2014

      you need to use jaxb.

      • naveen

        March 6, 2014

        lokesh but im getting xsd file using that as i mentioned.what i want is an xml file

        • Lokesh Gupta

          March 6, 2014

          You can refer, what I mean, here in few examples: https://howtodoinjava.com/jaxb/jaxb-annotations/

          OR//

          Give me a sample class and sample XML what you want in output.

  21. Roshan

    February 18, 2014

    Nice simple example. Helped me…

  22. vinayak

    December 6, 2013

    how to Junit this unmarshal object?

Comments are closed on this article!

Search Tutorials

JAXB Tutorial

  • JAXB – Annotations
  • JAXB – @XmlRootElement
  • JAXB – @XmlElementWrapper
  • JAXB – Marshaller
  • JAXB – Unmarshaller
  • JAXB – Convert XML to Java Object
  • JAXB – Convert JSON to Java Object
  • JAXB – Convert Java Object to XML
  • JAXB – Convert Java Object to JSON
  • JAXB – Map
  • JAXB – List and Set
  • JAXB – Generate Schema
  • JAXB – Schema Validation
  • JAXB – JAXBException
  • JAXB – IllegalAnnotationExceptions
  • JAXB – Marshal without @XmlRootElement
  • JAXB – Unmarshal without @XmlRootElement
  • Jackson 2 – Object from/to JSON
  • Jackson – Object from/to json
  • Jackson – JSON from/to Map

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces