How to Convert XML to JSON in Java

  1. Understanding XML and JSON
  2. Method 1: Using org.json Library
  3. Method 2: Using Jackson Library
  4. Conclusion
  5. FAQ
How to Convert XML to JSON in Java

Converting XML to JSON is a common task in software development, especially when dealing with web services and APIs. Java, being one of the most widely used programming languages, provides various libraries and tools to facilitate this process. Whether you’re working on a large-scale enterprise application or a simple project, understanding how to transform XML data into JSON format can significantly enhance data interchange and compatibility across different systems.

In this article, we’ll explore effective methods to convert XML to JSON in Java, complete with code examples and detailed explanations. Let’s dive in!

Understanding XML and JSON

Before we jump into the conversion process, it’s essential to understand what XML and JSON are. XML (eXtensible Markup Language) is a markup language designed to store and transport data. It is both human-readable and machine-readable. JSON (JavaScript Object Notation), on the other hand, is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.

The conversion from XML to JSON is often necessary because many modern web applications prefer JSON due to its simplicity and ease of use. This transformation can be achieved using various libraries in Java. Let’s look at a couple of methods to accomplish this.

Method 1: Using org.json Library

One of the simplest ways to convert XML to JSON in Java is by using the org.json library. This library offers a straightforward approach to handle JSON data and includes a utility for converting XML strings into JSON objects.

Step-by-Step Code Example

First, ensure you have the org.json library in your project. If you’re using Maven, you can add the following dependency to your pom.xml:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>

Next, you can use the following Java code to perform the conversion:

import org.json.JSONObject;
import org.json.XML;

public class XMLToJSONConverter {
    public static void main(String[] args) {
        String xml = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";
        JSONObject json = XML.toJSONObject(xml);
        System.out.println(json.toString(4));
    }
}

Output:

{
    "note": {
        "to": "Tove",
        "from": "Jani",
        "heading": "Reminder",
        "body": "Don't forget me this weekend!"
    }
}

The code above defines a simple XMLToJSONConverter class with a main method. It initializes an XML string representing a note. The XML.toJSONObject method converts the XML string into a JSONObject. Finally, the JSON object is printed in a pretty format with an indentation of 4 spaces.

This method is efficient and requires minimal setup, making it ideal for quick conversions. However, be mindful of the XML structure, as complex nested elements may require additional handling for accurate conversion.

Method 2: Using Jackson Library

Another powerful library for converting XML to JSON in Java is Jackson. Jackson is widely used for processing JSON and XML data. It provides a more flexible approach and can handle complex data structures effectively.

Step-by-Step Code Example

To get started with Jackson, add the following dependencies to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.13.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

Here’s how you can convert XML to JSON using Jackson:

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

public class XMLToJSONConverter {
    public static void main(String[] args) throws Exception {
        String xml = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";
        
        XmlMapper xmlMapper = new XmlMapper();
        JsonNode jsonNode = xmlMapper.readTree(xml.getBytes());
        
        ObjectMapper jsonMapper = new ObjectMapper();
        String json = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
        
        System.out.println(json);
    }
}

Output:

{
  "note" : {
    "to" : "Tove",
    "from" : "Jani",
    "heading" : "Reminder",
    "body" : "Don't forget me this weekend!"
  }
}

In this example, we first create an instance of XmlMapper to read the XML string into a JsonNode. Then, we use ObjectMapper to convert the JsonNode into a JSON string. The writerWithDefaultPrettyPrinter() method formats the output for better readability.

Jackson’s approach is more robust, allowing for easier handling of complex XML structures, including attributes and namespaces. It is well-suited for applications that require extensive data manipulation.

Conclusion

Converting XML to JSON in Java is a straightforward process, thanks to libraries like org.json and Jackson. Each method has its strengths, from simplicity and ease of use to flexibility and robustness. Depending on your project requirements, you can choose the one that best fits your needs. By mastering these conversion techniques, you can enhance your application’s data handling capabilities, making it easier to work with APIs and web services.

FAQ

  1. What is the main difference between XML and JSON?
    XML is a markup language used for data storage and transport, while JSON is a lightweight data interchange format that is easier to read and write.

  2. Can I use other libraries for XML to JSON conversion in Java?
    Yes, there are several libraries available, including Gson, Simple XML, and others, but org.json and Jackson are among the most popular.

  3. Do I need to handle XML namespaces during conversion?
    Yes, if your XML data contains namespaces, you may need to implement additional logic to handle them properly during conversion.

  4. Is the output format of JSON customizable?
    Yes, both org.json and Jackson allow you to customize the output format, including indentation and sorting of keys.

  5. Are there performance considerations when converting large XML files?
    Yes, performance may vary based on the library used and the complexity of the XML structure. It’s advisable to test with your specific data for optimal performance.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

Related Article - Java JSON

Related Article - Java XML