JAXB: Marshal / Unmarshal a Map in Java

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 the default in the case of the visual clients like web browsers.

A good example is Facebook APIs. Facebook has exposed its services through some open endpoints in the form of RESTful webservices where you hit a URL and post some parameters, and the API returns 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 Map object e.g. HashMap. These map objects usually represent the mapping between some simple keys to complex data.

1. Maven

Start with adding the latest ‘jakarta‘ dependencies for adding the JAXB support (Java 11 onwards).

<dependencies>
  <dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>4.0.0</version>
  </dependency>
</dependencies>

<dependencies>
  <dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>4.0.3</version>
    <scope>runtime</scope>
  </dependency>
</dependencies>

2. Model

I have created a model class “Employee.java” which has some common fields. I want to build code that could parse maps of objects where key is sequence code and value is Employee object itself.

@XmlRootElement(name = "employee")
@XmlAccessorType (XmlAccessType.FIELD)
public class Employee 
{
  private Integer id;
  private String firstName;
  private String lastName;
  private double income;
   
  //Getters and Setters
}
@XmlRootElement (name="employees")
@XmlAccessorType(XmlAccessType.FIELD)
public class EmployeeMap {
   
  private Map<Integer, Employee> employeeMap = new HashMap<Integer, Employee>();
 
  public Map<Integer, Employee> getEmployeeMap() {
    return employeeMap;
  }
 
  public void setEmployeeMap(Map<Integer, Employee> employeeMap) {
    this.employeeMap = employeeMap;
  }
}

3. Marshal Map to XML Example

Java example to marshal or convert java map to xml representation. In below example code, I am writing the map of employees first in console, and then in a file.

public static void main(String[] args) throws JAXBException 
{
  HashMap<Integer, Employee> map = new HashMap<Integer, Employee>();
   
  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);
   
  map.put( 1 , emp1);
  map.put( 2 , emp2);
   
  //Add employees in map
  EmployeeMap employeeMap = new EmployeeMap();
  employeeMap.setEmployeeMap(map);
   
  /******************** Marshalling example *****************************/
   
  JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeMap.class);
  Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
 
  jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 
  jaxbMarshaller.marshal(employeeMap, System.out);
  jaxbMarshaller.marshal(employeeMap, new File("c:/temp/employees.xml"));
}

The program output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees>
    <employeeMap>
        <entry>
            <key>1</key>
            <value>
                <id>1</id>
                <firstName>Lokesh</firstName>
                <lastName>Gupta</lastName>
                <income>100.0</income>
            </value>
        </entry>
        <entry>
            <key>2</key>
            <value>
                <id>2</id>
                <firstName>John</firstName>
                <lastName>Mclane</lastName>
                <income>200.0</income>
            </value>
        </entry>
    </employeeMap>
</employees>

4. Unmarshal XML to Map Example

Java example to convert xml to Java map object. Let’s see the example of our EmployeeMap class.

JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeMap.class);
  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  EmployeeMap empMap = (EmployeeMap) jaxbUnmarshaller.unmarshal( new File("c:/temp/employees.xml") );
   
  for(Integer empId : empMap.getEmployeeMap().keySet())
  {
    System.out.println(empMap.getEmployeeMap().get(empId).getFirstName());
    System.out.println(empMap.getEmployeeMap().get(empId).getLastName());
  }

The program output:

Lokesh
Gupta
John
Mclane

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
28 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode