How to convert XML to JSON in Java

In this tutorial, we will learn how to convert XML data to JSON data in Java. Using a simple Java program we can easily convert XML data to JSON data.

XML stands for eXtensible Markup Language. It is a markup language like HTML, basic difference between these two is the HTML focuses on how the data looks whereas, XML focuses on what the data is. It is self-descriptive and was designed to store and transport data.
Example of XML:

<college>
  <student>
    <id>101</id>
    <name>abc</name>
    <branch>CS</branch>
  </student>
  <student>
    <id>102</id>
    <name>xyz</name>
    <branch>IT</branch>
  </student>
</college>

Whereas, JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. JSON is “self-describing” and easy to understand. Where data is stored in key/value pairs and is stored by commas, curly braces hold objects and square brackets hold arrays.
Example of JSON:

{
"college"{
  "student"[
    {"name":"abc","id":101,"branch":"CS"},
    {"name":"xyz","id":102,"branch":"IT"}
  ]
}
}

Converting XML to JSON in Java

following are the basic steps we need to follow:

  • Firstly create a maven project.
  • Add dependency in pom.xml. Add the following dependency:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
  • Import org.json package for JSON.
  • Create a string variable to store XML data.
  • Now to convert XML to JSON create JSONObject and convert using XML.toJSONObject(XMLvariable).
  • Finally, print JSONObject.

Following is the code:

import org.json.*;	
public class xmltojson {

  public static String x="<college><student><id>101</id><name>abc</name><branch>CS</branch></student><student><id>102</id><name>xyz</name<branch>IT</branch></student></college>";
  
  public static void main(String[] args)  {  
    JSONObject json=XML.toJSONObject(x); 
    System.out.println(json);	
  }  
}

Output:

{"college":{"student":[{"name":"abc","id":101,"branch":"CS"},{"name":"xyz","id":102,"branch":"IT"}]}}

This is how we have successfully able to convert XML data into JSON formatted data. I hope you find this tutorial useful.

One response to “How to convert XML to JSON in Java”

  1. Valentyn says:

    Underscore-java library has a static method U.xmlToJson(xml).

Leave a Reply

Your email address will not be published. Required fields are marked *