Overview
In this tutorial, we show you how to convert XML to JSON in Java using Eclipse IDE. Used org.json.XML class from json-20170516.jarVideo Tutorials
Project Structure
Create New Java Project
- Launch Eclipse IDE.
- Go to File-> New-> Others... Select Java Project then click Next.
- Type ConvertXmlToJson in the "Project name" field.
- Click Finish.
Adding org.json.* lib to an Eclipse Project Folder
- Right click this project
- Select Bulid Path -> Configure Build Path...
- Under Libraries tab, click Add JARS... or Add External JARs... and give the json-20170516.jar jar file
- Click Apply
- Click OK
Create Xml2Json Class
Create a Xml2Json class under com.jackrutorial package and write the following code in it.package com.jackrutorial;
import org.json.JSONObject;
import org.json.XML;
public class Xml2Json {
private static final int PRETTY_PRINT_INDENT_FACTOR = 4;
public static void main(String[] args){
String xmlString = "Test 1 25 Test 2 26 ";
JSONObject jsonObject = XML.toJSONObject(xmlString);
String jsonPrettyPrintString = jsonObject.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
}
}
As shown above, we will convert User XML to JSON Object
<users> <user> <name>Test 1</name> <age>25</age> </user> <user> <name>Test 2</name> <age>26</age> </user> </users>
Run the Program
- Right click to the class select Run As -> Java Application.
Output
{
"users": {
"user": [
{
"name": "Test 1",
"age": 25
},
{
"name": "Test 2",
"age": 26
}
]}
}
