Java – How to convert XML to JSON using JSONObject ?

In this article, we will discuss how to convert XML file to JSON file using JSONObject

1. Required libraries :

1.1 Maven Co-ordinates :

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

1.2 JAR files to download :

Download below jar files and include them in Project classpath

1.3 Project class-path :

2. XML to JSON conversion :

In the below illustration, we will convert XML to JSON file using JSONObject,

  • 1st step is to read the contents of the XML file to a String object
  • 2nd step is to convert String into JSON using XML.toJSONObject(xmlString) method with indentation of 4 for pretty printing
  • 3rd step is to store converted JSON into a file using Files.write() method passing 2 input-arguments
    • File location
    • JSON String contents in bytes format

XML file contents – Person.xml:

<firstName>Sam</firstName>
<lastName>Anton</lastName>
<address>
	<nodeName>South Bengaluru</nodeName>
	<buildingName>Shivaji</buildingName>
	<country>India</country>
	<city>Bengaluru</city>
	<flatNumber>BV-1025</flatNumber>
	<plotNumber>1093</plotNumber>
	<state>Karnataka</state>
	<sector>Sector 19</sector>
</address>
<title>Mr.</title>
<items>
	<itemName>Television</itemName>
	<itemBoughtYear>2014</itemBoughtYear>
</items>
<items>
	<itemName>Washing Machine</itemName>
	<itemBoughtYear>2020</itemBoughtYear>
</items>
<items>
	<itemName>Refrigerator</itemName>
	<itemBoughtYear>2011</itemBoughtYear>
</items>
<items>
	<itemName>Grinder</itemName>
	<itemBoughtYear>2012</itemBoughtYear>
</items>
<items>
	<itemName>Computer</itemName>
	<itemBoughtYear>2010</itemBoughtYear>
</items>

XmlToJsonConversion.java

package in.bench.resources.yaml.conversion;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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

public class XmlToJsonConversion {

	public static void main(String[] args) {

		try {
			// 1st step - read XML contents
			String xmlContent = new String(Files.readAllBytes(Paths.get(
					"C:\\Users\\Demo\\eclipse-workspace\\YamlConversion\\Person.xml")));


			// 2nd step - convert XML to JSON
			String jsonString = convertXmlToJson(xmlContent);


			// print to console
			System.out.println("XML to JSON conversion :- \n\n" + jsonString);


			// store converted JSON file
			storeConvertedJsonInFile(jsonString);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 * This method converts XML String to formatted JSON
	 * 
	 * @param xml
	 * @return
	 */
	private static String convertXmlToJson(String xml) {

		// create JSONObject
		JSONObject jsonObject = XML.toJSONObject(xml);


		// return formatted JSON
		return jsonObject.toString(4);
	}


	/**
	 * This method stores converted JSON in Project class-path
	 * 
	 * @param jsonString
	 */
	private static void storeConvertedJsonInFile(String jsonString) {

		// define path to write Json file
		Path filename = Paths.get(
				"C:\\Users\\Demo\\eclipse-workspace\\YamlConversion\\XML_to_JSON_Person.json");

		try {

			// write to the above file path
			Files.write(filename, jsonString.getBytes());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output in console :

XML to JSON conversion :- 

{
    "firstName": "Sam",
    "lastName": "Anton",
    "address": {
        "nodeName": "South Bengaluru",
        "buildingName": "Shivaji",
        "country": "India",
        "city": "Bengaluru",
        "flatNumber": "BV-1025",
        "plotNumber": 1093,
        "state": "Karnataka",
        "sector": "Sector 19"
    },
    "title": "Mr.",
    "items": [
        {
            "itemName": "Television",
            "itemBoughtYear": 2014
        },
        {
            "itemName": "Washing Machine",
            "itemBoughtYear": 2020
        },
        {
            "itemName": "Refrigerator",
            "itemBoughtYear": 2011
        },
        {
            "itemName": "Grinder",
            "itemBoughtYear": 2012
        },
        {
            "itemName": "Computer",
            "itemBoughtYear": 2010
        }
    ]
}

Converted JSON file -> XML_to_JSON_Person.json

{
    "firstName": "Sam",
    "lastName": "Anton",
    "address": {
        "nodeName": "South Bengaluru",
        "buildingName": "Shivaji",
        "country": "India",
        "city": "Bengaluru",
        "flatNumber": "BV-1025",
        "plotNumber": 1093,
        "state": "Karnataka",
        "sector": "Sector 19"
    },
    "title": "Mr.",
    "items": [
        {
            "itemName": "Television",
            "itemBoughtYear": 2014
        },
        {
            "itemName": "Washing Machine",
            "itemBoughtYear": 2020
        },
        {
            "itemName": "Refrigerator",
            "itemBoughtYear": 2011
        },
        {
            "itemName": "Grinder",
            "itemBoughtYear": 2012
        },
        {
            "itemName": "Computer",
            "itemBoughtYear": 2010
        }
    ]
}

In the following article, we will discuss same XML to JSON conversion using Jackson or ObjectMapper in detail

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java – How to convert JSON to XML using JSONObject ?
Java – How to convert JSON to YAML using ObjectMapper ?