Sai A Sai A
Updated date Jul 29, 2023
In this blog, we will learn how to simplify Java XML to JSON array conversion. The blog covers two methods, one using external libraries like Jackson or Gson for quick and robust conversions, and the other using the DOM parser for more manual control.

Introduction:

In this blog, we will explore two methods to convert XML data into JSON arrays in Java, along with step-by-step explanations and sample code. By the end of this guide, you will have a clear understanding of how to streamline this conversion process, making your Java projects more developer-friendly and versatile.

Method 1: Using External Libraries

The first method involves leveraging powerful external libraries like Jackson or Gson, which provide robust XML-to-JSON conversion utilities. These libraries abstract away the complexities of conversion, allowing us to focus on our application logic.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class XmlToJsonWithJackson {
    public static void main(String[] args) {
        try {
            String xmlData = "<root><item>value1</item><item>value2</item></root>";
            XmlMapper xmlMapper = new XmlMapper();
            JsonNode node = xmlMapper.readTree(xmlData.getBytes());
            ObjectMapper jsonMapper = new ObjectMapper();
            String jsonData = jsonMapper.writeValueAsString(node);
            System.out.println(jsonData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output and Explanation:

The output of the above program will be a JSON array: {"root":{"item":["value1","value2"]}}. Here, we first parse the XML data into a Jackson JsonNode using the XmlMapper, and then convert it to a JSON string with the ObjectMapper.

Method 2: Manual Conversion with DOM Parser

The second method involves manually parsing the XML data using the DOM (Document Object Model) parser and constructing the JSON array accordingly.

import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

public class XmlToJsonWithDOMParser {
    public static void main(String[] args) {
        try {
            String xmlData = "<root><item>value1</item><item>value2</item></root>";
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(new StringReader(xmlData));
            Document doc = builder.parse(inputSource);
            Element root = doc.getDocumentElement();
            NodeList items = root.getElementsByTagName("item");
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < items.getLength(); i++) {
                Element item = (Element) items.item(i);
                jsonArray.put(item.getTextContent());
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("root", jsonArray);
            System.out.println(jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output and Explanation:

The output of the above program will be the same as the previous method: {"root":["value1","value2"]}. Here, we manually traverse the DOM tree, extract the values of <item> elements, and construct a JSON array using the JSONArray class and a JSON object using the JSONObject class.

Conclusion:

In this blog, we explored two methods for converting XML data into JSON arrays in Java. The first method utilized external libraries like Jackson or Gson, simplifying the conversion process with ready-to-use utility classes. The second method demonstrated a manual approach using the DOM parser, which can be useful for simpler XML structures.

Comments (0)

There are no comments. Be the first to comment!!!