Convert XML to JSON in Java
In this quick article, we’ll explore how to convert XML to JSON in Java.
Java community didn’t provide any capability to convert XML to JSON in standard JDK. However, several third-party libraries are available for conversion between JSON and XML.
We can use the org.json.XML class from JSON in Java package to convert an XML to JSON in Java. Following is a simple example demonstrating usage of this library:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import org.json.JSONException; import org.json.JSONObject; import org.json.XML; class Main { public static int INDENTATION = 4; public static String XML_STRING = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<root>" + "<firstName>John</firstName>" + "<lastName>Snow</lastName>" + "<age>25</age>" + "<spouse/>" + "<address>" + "<street>237 Harrison Street</street>" + "<city>Brooklyn, NY</city>" + "<state>New York</state>" + "<postalCode>11238</postalCode>" + "</address>" + "<phoneNumbers>" + "<type>mobile</type>" + "<number>212 555-3346</number>" + "</phoneNumbers>" + "<phoneNumbers>" + "<type>fax</type>" + "<number>646 555-4567</number>" + "</phoneNumbers>" + "</root>"; public static void main(String[] args) { try { JSONObject jsonObj = XML.toJSONObject(XML_STRING); String json = jsonObj.toString(INDENTATION); System.out.println(json); } catch (JSONException ex) { ex.printStackTrace(); } } } |
Output:
{
"root": {
"firstName": "John",
"lastName": "Snow",
"address": {
"city": "Brooklyn, NY",
"street": "237 Harrison Street",
"postalCode": 11238,
"state": "New York"
},
"age": 25,
"spouse": "",
"phoneNumbers": [
{
"number": "212 555-3346",
"type": "mobile"
},
{
"number": "646 555-4567",
"type": "fax"
}
]
}
}
Before we wind up this post, here’s the maven dependency for JSON In Java.
|
1 2 3 4 5 6 7 |
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180813</version> <type>bundle</type> </dependency> |
That’s all about converting XML to JSON in Java.
Also See: Convert XML to JSON online
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)