HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / JAXB / JAXB – Marshal and Unmarshal HashMap in Java

JAXB – Marshal and Unmarshal HashMap 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 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 Map object e.g. HashMap. These map objects are usually represent the mapping between some simple keys to complex data.

1) JAXB Maven Dependencies

To run JAXB examples, we need to add run time 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) Map model classes

I have created a model class “Employee.java” which has some common fields. I want to build code which could parse map 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
}
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 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"));
}

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.

private static void unMarshalingExample() throws JAXBException 
{
	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());
	}
}
	
Output:

Lokesh
Gupta
John
Mclane

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

    August 3, 2016

    how to use only the name of xml file without giving the full path address in unMarshalingExample() ?

  2. abhi

    August 3, 2016

    what to do if wanna call xml file only by its name not by full path address?

  3. Srinivasarao Dupati

    February 22, 2016

    i want learn Data Structures and Algorithms and I want know which algorithm is better for which Data Structures also….. please give me Best Reference to learn Time Complexity and Space Complexity also…..

    • Lokesh Gupta

      February 22, 2016

      Not sure. I still have not gone through any resource/book which I can recommend.

      • Srinivasarao Dupati

        February 22, 2016

        Ok But as per your point of view you can prefer one book, so Just give me any one based on your experience level to refer, it could be Commercial also fine or Open Source also fine…

        I want grow up my Skills, i am trying for 6 months but i did’t find So please help me ……

  4. Srinivasarao Dupati

    February 9, 2016

    Hi Lokesh good evening ,

    thank you for Sharing Content here and giving reply for to US.
    i got one Business case, that I have to Develop one Web Service and That Web Service Will have to as SOAP(JAX-RS) Web Service and as well as REST full web Service, to get the Solution i am referring JAX-RS Spec and SOAP(JAX-RS) Spec, But i could n’t able to find the Solution . So can you help me Here.

    Thanking you.

    • Lokesh Gupta

      February 9, 2016

      You will need to develop two web services with almost similar contract.

      • Srinivasarao

        February 10, 2016

        Hi Lokesh,

        Yes, but at the SOAP Point of view we can See WSDL, But JAX-RS API , Resteasy Impl will not support the any WSDl and WADL, in this case one Contract is not usefull.

        here i have some doubts, IF we develop the SOAP Web Service then the Web Service will not take the GET method , Bcoz the Complexity xml Data we cant send over the Get method String Query param, So that the SOAP failed Here as per my knowledge, is there any alternative tools are there in market to support the above business case, please tell me.

        • Lokesh Gupta

          February 10, 2016

          I am not aware of any such tool or methodology.

          • Srinivasarao Dupati

            February 10, 2016

            OK thanks for your answer,
            is it possible to build one web Service and that could be work as SOAP and REST Web Service

            • Lokesh Gupta

              February 10, 2016

              Not really!! Both are too much different with very less in common.

              • Srinivasarao Dupati

                February 22, 2016

                Which algorithm is better for sorting Linked List and Searching the Element in Linked list

                • Lokesh Gupta

                  February 22, 2016

                  Perhaps MergeSort will give you best results in case of LinkedList. It has been established many times by many researchers e.g. here.

  5. Ganga

    December 26, 2015

    Hi,

    This is a very good article which helped through the issue I have been struggling with a few days now.

    How can I get rid of the unwanted tags , 1 and from the output xml and only retain the actual Employee related Tags.

    Thanks,
    Ganga

    • Ganga

      December 26, 2015

      Sorry, looks like the tags that I was referring to in the Query I posted did not display quite well . The tags that I am referring to are

      1. Entry
      2. Key
      3. Value

      • Ganga

        December 26, 2015

        I found a solution for this..I used Arraylist instead of Map…I added all the map values into Arraylist before passing it to jaxb marshaller…
        Thanks,
        Ganga

        • Lokesh Gupta

          December 27, 2015

          Seems good to me.

  6. Rahul Gupta

    November 26, 2015

    I have one ParentItem.java class having common attributes and 2 child classes Merchandise.java and Offer.java. I have one Transaction.java class having list of ParentItem, so as to marshal list of 2 different object and want to get structure like this :

    LINE_ITEM
    ADD
    1
    REG2
    7.00
    7.42
    0.42

    5.00
    #1 Combo Meal
    1695155651
    5.00
    1

    5.00
    #1 Combo Meal
    1695155652
    5.00
    1

    OTHER_COUPON
    1695155653
    EmpDisc
    2.00
    1695155651

    MERCHANT_COUPON
    1695155654
    1OffAnyPurch
    1.00
    1695155651

    but doing all my stuff of coding I am getting following structure:

    ADD
    LINE_ITEM

    TIE WAIST SHIRT DRESS
    1

    Offer
    100

  7. muhabbul Haasan

    March 5, 2015

    How i create a java client now to view all the employee and perform an simple query

    • Lokesh Gupta

      March 5, 2015

      Java client for what purpose??

      • hasan

        March 5, 2015

        to retrive employee information.

  8. Ankush

    May 9, 2014

    Ankush

    I want output is like that as PFB

    Employees e =
    e.getFirstName() = “Ankush”
    e.getAddress() = “>”

    how can get this result from jaxb

    • Lokesh Gupta

      May 9, 2014

      Something missing in comment. I am not able to understand it properly.

  9. Zamir Hasan

    February 16, 2014

    Hi Lokesh,

    Could you please help me with the below XML structure where the below block would be repeated many times depending upon the condition.

    ABC

    .

    Many Thanks!

    • Nitish

      September 24, 2014

      Hi Lokesh i am getting the following error while sending the @requestline(get test/search?userid={userId}deptid={deptid}

      unable to marshal type “java.util.LinkedHashMap” as an element because it is missing an @XmlRootElement annotation

      • Lokesh Gupta

        September 24, 2014

        You can return an instance of LinkedHashMap from your method because it does not contain @XmlRootElement annotation. You must return an instance of class which has @XmlRootElement annotation and add LinkedHashMap as an attribute in this class (with setters and getters).
        https://dzone.com/articles/jaxb-and-javautilmap has some good examples.

        • Nitish

          September 24, 2014

          I need to send only couple of parameters but still facing the problem

          • Lokesh Gupta

            September 24, 2014

            Doesn’t matter the number of parameters. The class you return from method “MUST” have @XmlRootElement annotation.

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