Quickest way to convert XML to JSON in Java [closed] Quickest way to convert XML to JSON in Java [closed] json json

Quickest way to convert XML to JSON in Java [closed]


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"}}


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);


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).