Java Jackson XML to Map

1. Introduction

Converting XML content to a Java Map can be a useful technique when the XML structure is either too dynamic or you do not wish to create a specific POJO for it. Jackson’s XML module makes this relatively straightforward. In this post, we'll demonstrate how to convert XML content into a Java Map using the Jackson library.

2. Program Steps

1. Include necessary Jackson XML dependencies in your project.

2. Utilize XmlMapper to read the XML content.

3. Convert the XML content to a Map object.

4. Display the resulting map.

3. Code Program

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.util.Map;

public class JacksonXmlToMapExample {

    public static void main(String[] args) {
        try {
            // Sample XML content
            String xmlString = "<product><name>Laptop</name><price>1200.5</price></product>";

            // Create XmlMapper instance
            XmlMapper xmlMapper = new XmlMapper();

            // Convert XML string to Map
            Map<String, Object> map = xmlMapper.readValue(xmlString, Map.class);

            System.out.println("Converted Map: " + map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Converted Map: {product={name=Laptop, price=1200.5}}

4. Step By Step Explanation

1. The XML content we intend to convert is a simple product structure with a name and a price.

2. We use Jackson's XmlMapper class, which is specifically tailored for handling XML data. An instance of XmlMapper is created.

3. The readValue method of XmlMapper is then invoked, passing in the XML string and specifying that we want the result as a Map.

4. Finally, the converted map is printed. As observed, the root XML element (product) becomes the main key in the map, and its child elements are represented as key-value pairs inside a nested map.

This technique can be particularly useful when you have XML content with varying structures, as it provides a flexible way to represent XML as key-value pairs without needing a specific Java class representation.


Comments