Overview
In this tutorial, we show you how to convert JSON Object to XML in Java using Eclipse IDEVideo Tutorials
Project Structure
Create New Java Project
- Launch Eclipse IDE.
- Go to File-> New-> Others... Select Java Project then click Next.
- Type ConvertJsonToXml in the "Project name" field.
- Click Finish.
Adding 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 Json2Xml Class
Create a Json2Xml class under tutorial4u.example package and write the following code in it
package tutorial4u.example;
import org.json.JSONObject;
import org.json.XML;
public class Json2Xml {
public static void main(String args[]){
StringBuilder jsonObj = new StringBuilder(" ");
jsonObj.append("{ ");
jsonObj.append(" \"users\": { ");
jsonObj.append(" \"user\": [ ");
jsonObj.append(" { ");
jsonObj.append(" \"name\": \"Test 1\", ");
jsonObj.append(" \"age\": 20 ");
jsonObj.append(" }, ");
jsonObj.append(" { ");
jsonObj.append(" \"name\": \"Test 2\", ");
jsonObj.append(" \"age\": 21 ");
jsonObj.append(" } ");
jsonObj.append(" ] ");
jsonObj.append(" } ");
jsonObj.append("} ");
JSONObject json = new JSONObject(jsonObj.toString());
String xml = XML.toString(json);
System.out.println("JSON converted to XML: ");
System.out.println(xml);
}
}
As shown above, in this tutorial we will convert User Object JSON to XML
{
"users": {
"user": [
{
"name": "Test 1",
"age": 20
},
{
"name": "Test 2",
"age": 21
}
]
}
}
Run & Check result
Right click to the Json2Xml class, select Run As -> Java Application
Output
JSON converted to XML: <users> <user> <name>Test 1</name> <age>20</age> </user> <user> <name>Test 2</name> <age>21</age> </user> </users>

