Converting XML to JSON in Java
In this post, We will show you simple program about, How to Convert XML to JSON in Java. The example program has been tested and shared in the same post.
Maven Dependency
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20170516</version> </dependency>
Example Program
package com.dineshkrish; import java.io.File; import java.io.IOException; import java.nio.file.Files; import org.json.JSONObject; import org.json.XML; /** * * @author Dinesh Krishnan * */ public class Converter { // Converting XML to JSON public static JSONObject convert(String xml) { if(xml == null || xml.isEmpty()) { return null; } return XML.toJSONObject(xml); } public static void main(String[] args) { final String fileName = "input.xml"; File xmlFile = new File(fileName); try { byte[] b = Files.readAllBytes(xmlFile.toPath()); String xml = new String(b); JSONObject obj = convert(xml); System.out.println(obj); } catch (IOException e) { e.printStackTrace(); } } }
Sample Input
<?xml version="1.0" encoding="UTF-8"?> <employee> <empId>101</empId> <empName>John</empName> <empAge>10</empAge> <empEmail>dinesh@idineshkrishnan.com</empEmail> <empPhone>+91 9941937705</empPhone> <Address> <doorNo>10</doorNo> <city>Chennai</city> <state>Tamilnadu</state> <country>India</country> </Address> </employee>
Output
{ "employee": { "empId": 101, "empPhone": "+91 9941937705", "Address": { "country": "India", "city": "Chennai", "doorNo": 10, "state": "Tamilnadu" }, "empName": "John", "empEmail": "dinesh@idineshkrishnan.com", "empAge": 10 } }
Reference
1. Quickest way to convert XML to JSON in Java – Stack Overflow
2. Convert JSON to Object
3. JSON and JSON Structure
4. XML and XML Structure
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet