What are some good tools for quickly and easily converting XML to JSON in Java?
-
i can't use XML directly due to a requirement in the spec, but i agree with you. thanks! – BeachRunnerFred Dec 01 '09 at 00:29
-
@BeachRunnerJoe : What import do I need to write? `import net.sf.json.JSONObject;` or `import org.json.JSONObject;`. Also which jar do I need to include? – Fahim Parkar Jun 03 '12 at 16:20
-
1Here's a link to a way to do it without any dependencies, using JAXP: http://stackoverflow.com/questions/27222992/convert-xml-string-to-json-string-without-using-third-party-libs/30807545#30807545 – bvdb Jun 12 '15 at 16:08
-
If you have a valid dtd file for the xml snippet, then you can easily convert xml to json and json to xml using the open source eclipse link jar. Detailed sample JAVA project can be found here: cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html – Piyush Chordia Apr 24 '16 at 16:59
-
26I love SO's closed questions that have such very high visibility... Something went wrong somewhere if such a useful question was closed. – Dariusz May 09 '17 at 07:18
-
4i think 90% of the most useful questions are "Closed-off topic"..smh – Jeryl Cook Nov 12 '17 at 14:26
-
Underscore-java has a static method U.xmlToJson(xml). – Valentyn Kolesnikov Oct 11 '21 at 09:29
6 Answers
JSON in Java has some great resources.
Maven dependency:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
XML.java
is the class you're looking for:
import org.json.JSONObject;
import org.json.XML;
import org.json.JSONException;
public class Main {
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String TEST_XML_STRING =
"<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to JSON</test>";
public static void main(String[] args) {
try {
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
} catch (JSONException je) {
System.out.println(je.toString());
}
}
}
Output is:
{"test": {
"attrib": "moretest",
"content": "Turn this to JSON"
}}

- 155
- 1
- 8

- 7,752
- 5
- 39
- 60
-
14
-
2@danieltalsky : What import do I need to write? `import net.sf.json.JSONObject;` or `import org.json.JSONObject;`. Also which jar do I need to include? – Fahim Parkar Jun 03 '12 at 16:15
-
2download all the files not just XML.java. From here: https://github.com/douglascrockford/JSON-java/downloads – Spiff Oct 18 '12 at 15:37
-
4
-
@WChargin it would be something like {"test":{"content":["foo","bar"],"attrib":"moretest"}}, i.e. the 'content' will become an array as it would not be able to distinguish between inner attribute and body. – dotrc Oct 14 '15 at 04:22
-
1NOTE: org.json's XML.toJSONObject() also correctly converts xml lists to json arrays (unlike jackson's XmlMapper which by default silently swallows). – Agoston Horvath Oct 07 '16 at 09:33
-
I had to copy the entire JSON package to my project and renamed the package. Adding to gradle gives warning of duplicate package from Android during build. – codelearner Oct 09 '16 at 11:03
-
java.lang.OutOfMemoryError: Java heap space exception when tried to convert GB size XML file. Heap Size increase won't help either. – Ankit May 10 '18 at 16:45
-
Any idea how Pascal case XML fields can be converted to Camel case using this approach? – Jestino Sam Apr 07 '21 at 08:55
-
Underscore-java has a static method U.xmlToJson(xmlstring). – Valentyn Kolesnikov Jul 03 '21 at 07:20
-
BEWARE those doing Evil. The JSON License expressly prohibits use for Evil. https://www.json.org/license.html – Dan Rayson Jul 13 '21 at 14:43
To convert XML File in to JSON include the following dependency
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
and you can Download Jar from Maven Repository here. Then implement as:
String soapmessageString = "<xml>yourStringURLorFILE</xml>";
JSONObject soapDatainJsonObject = XML.toJSONObject(soapmessageString);
System.out.println(soapDatainJsonObject);

- 20,434
- 21
- 120
- 152

- 3,429
- 5
- 34
- 68
-
6
-
2use the version of json mentioned in the post if you are on java 7 as latest version throws weird errors. – urug Oct 02 '15 at 19:56
-
If you have a valid dtd file for the xml snippet, then you can easily convert xml to json and json to xml using the open source eclipse link jar. Detailed sample JAVA project can be found here: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html – Piyush Chordia Feb 25 '16 at 08:51
-
I had to copy the entire JSON package to my project and renamed the package. Adding to gradle gives warning of duplicate package from Android during build. – codelearner Oct 09 '16 at 11:04
The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, but if it has 2+, you return an array, which can cause parsing issues for people using the JSON.
Infoscoop's XML2JSON class has a way of tagging elements that are arrays before doing the conversion, so that arrays can be properly mapped, even if there is only one child in the XML.
Here is an example of using it (in a slightly different language, but you can also see how arrays is used from the nodelist2json() method of the XML2JSON link).

- 2,128
- 20
- 22
-
we are using an "xml-to-json" library in python and this is a semantic problem. What we do to solve this "array or object" problem , is writing a "tryConvertToArray()" method , which returns an array with the single object in it. So , you can always trust your value to be an array – kommradHomer May 29 '13 at 12:18
-
It's not clear to me how that solves the problem. Do you just make everything an array instead of an object then? E.g., if I have the XML `
`, would it generate `{ "results" : { "result" : { "value" : "1" } } }` or `{ "results" : [ { "result" : { "value" : "1" } } ] }` – Marcus Jun 17 '13 at 21:561 -
There is something that we expect it to be an array. The problem arises when this array has only 1 element , making it an object for the xml-to-json converter. So , as we expect this to be an array for even a single element , we check and convert it to an array , making sure we have an array where we expect an array. – kommradHomer Jun 18 '13 at 06:05
-
But how do you expect for a specific element to be an array? XML2JSON tags the elements. It's not clear how to expect it to be an array without tagging it, since otherwise you'd never know with a single element 'array'. – Marcus Jun 22 '13 at 00:14
-
For example , there is an element called "phonenumbers" . And there are 1 or more "phonenumber" elements in "phonenumbers" element. So when theres only one "phonenumber" element in "phonenumbers" , xml2json creates a phonenumber object , but i create a phonenumber array and put the phonenumber object in it. – kommradHomer Jun 22 '13 at 19:48
-
Understood, and this is how XML2JSON works as well. However, most parsers will assume that phonenumbers is an array, not an object. Wouldn't your solution not make phonenumbers an array when it only contains a single phonenumber element? Most consumers of the JSON won't always check whether it's an array or object, and assume it to be an array, causing problems for cases when there's only one 'phonenumber' in 'phonenumbers'. – Marcus Jul 08 '13 at 18:36
-
@danieltalsky My xml contains attribute value "0123" after conversion from xml to json, value become 123. I want 0123 as it is. How can i do that ? – StackOverFlow Aug 08 '13 at 08:30
-
-
@xydev Please check http://stackoverflow.com/questions/18121714/xml-to-json-conversion-issue-in-java-1st-leading-zero-discarded-fom-string#comment26539320_18121714 – StackOverFlow Aug 19 '13 at 06:28
-
-
You can refer here to convert XML to JSON, it encloses all the JSONObject to an JSONArray https://stackoverflow.com/a/61816190/4481302 – Nalam May 15 '20 at 09:43
I found this the quick and easy way:
Used: org.json.XML
class from java-json.jar
if (statusCode == 200 && inputStream != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = bufferedReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
jsonObject = XML.toJSONObject(responseStrBuilder.toString());
}
I have uploaded the project you can directly open in eclipse and run that's all https://github.com/pareshmutha/XMLToJsonConverterUsingJAVA
Thank You
-
In case anyone needed an online tool here's one https://json2csharp.com/xml-to-java – Hilal Jan 07 '21 at 09:33
I don't know what your exact problem is, but if you're receiving XML and want to return JSON (or something) you could also look at JAX-B. This is a standard for marshalling/unmarshalling Java POJO's to XML and/or Json. There are multiple libraries that implement JAX-B, for example Apache's CXF.

- 3,658
- 3
- 31
- 40

- 728
- 1
- 4
- 14