What are some good tools for quickly and easily converting XML to JSON in Java?
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"
}}
-
14
-
2@danieltalsky : What import do I need to write?
import net.sf.json.JSONObject;
orimport org.json.JSONObject;
. Also which jar do I need to include? Jun 3, 2012 at 16:15 -
2download all the files not just XML.java. From here: github.com/douglascrockford/JSON-java/downloads– SpiffOct 18, 2012 at 15:37
-
4
-
1NOTE: org.json's XML.toJSONObject() also correctly converts xml lists to json arrays (unlike jackson's XmlMapper which by default silently swallows). Oct 7, 2016 at 9:33
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);
-
6
-
2use the version of json mentioned in the post if you are on java 7 as latest version throws weird errors.– urugOct 2, 2015 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: cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html Feb 25, 2016 at 8: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. Oct 9, 2016 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).
-
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 May 29, 2013 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
<results><result><value>1</value></result></results>
, would it generate{ "results" : { "result" : { "value" : "1" } } }
or{ "results" : [ { "result" : { "value" : "1" } } ] }
– MarcusJun 17, 2013 at 21:56 -
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. Jun 18, 2013 at 6: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'.– MarcusJun 22, 2013 at 0: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. Jun 22, 2013 at 19:48
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 json2csharp.com/xml-to-java– HilalJan 7, 2021 at 9: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.
import net.sf.json.JSONObject;
orimport org.json.JSONObject;
. Also which jar do I need to include?