All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Convert XML To JSON In Java

Last Updated : Sep 9, 2023

How To Convert XML To JSON In Java

In this article we will show you the solution of how to convert XML to JSON in java, various libraries and techniques can be used in Java to convert XML to JSON. One typical method is combining a JSON library like Jackson or Gson with the Java API for XML Processing (JAXP).

In order to extract the required data, the method often entails parsing the XML document using an XML parser, such as DOM or SAX.

Next, a JSON representation of the extracted data is created. You can accomplish this by producing a JSON object or by utilising a mapping technique offered by the JSON library.

The relevant XML and JSON libraries would first need to be added to your Java project.

The XML parser can then be used to extract the data from the XML document.

Once the data is available, it may be converted into a JSON representation using the JSON library. Now we'll discuss the idea of java xml to json conversion.

Step By Step Guide On How To Convert XML To JSON In Java :-

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.File;
import java.io.IOException;
public class XMLtoJSONConverter {
    public static void main(String[] args) {
        try {
            // Create ObjectMapper instances for XML and JSON
            XmlMapper xmlMapper = new XmlMapper();
            ObjectMapper jsonMapper = new ObjectMapper();
            jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);
            // Read XML file into a JsonNode
            JsonNode xmlNode = xmlMapper.readTree(new File("input.xml"));
            // Convert XML to JSON
            String json = jsonMapper.writeValueAsString(xmlNode);
            // Write JSON to output file
            jsonMapper.writeValue(new File("output.json"), jsonNode);
            System.out.println("XML to JSON conversion completed successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. We begin by importing the required classes from the Jackson library, including JsonNode, ObjectMapper, SerializationFeature, ObjectNode, and 'XmlMapper.
  2. These classes offer the ability to operate with XML and JSON data.
  3. We create the XMLtoJSONConverter class, which includes the main method for converting XML to JSON.
  4. We create an instance of both XmlMapper and ObjectMapper inside the main procedure.
  5. The Jackson library offers these ObjectMapper classes, of which XmlMapper is used for reading XML data and ObjectMapper for producing JSON data.
  6. The command jsonMapper.enable(SerializationFeature.INDENT_OUTPUT); allows pretty printing of the generated JSON, which adds indentation to make it easier to read by humans.
  7. The readTree function of the XmlMapper class is used to read the XML file into a JsonNode object.
  8. This method extracts the data from the XML file and creates a tree-like structure out of JsonNode objects to represent it.
  9. The JsonNode object containing the XML data is transformed into a JSON string using the jsonMapper.writeValueAsString method.
  10. Using the writeValue method of jsonMapper, the final JSON string is written to an output file with the name "output.json."
  11. In the event that the XML to JSON conversion goes smoothly, we output a success message to the console.
  12. We catch the exception and publish the stack trace whenever an IOException happens while reading, writing, or converting files.

Conclusion :-

As a result, we have successfully learnt the Java idea of converting XML to JSON.

Additionally, we discovered how simple it is for developers to edit and analyse XML data in the widely used JSON format, making it easier to integrate with multiple systems and APIs.

I hope this article on how to convert XML to JSON in java helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Anjali

Experienced Computer Programmer with a broad range of experience in technology. Strengths in application development and Object Oriented architecture design, front end programming, usability and multimedia technology. Expert in coding languages such as C, C++ Java, JavaScript, PHP and more.

Follow Anjali On Linkedin 🡪