187

What are some good tools for quickly and easily converting XML to JSON in Java?

7
  • i can't use XML directly due to a requirement in the spec, but i agree with you. thanks! Dec 1, 2009 at 0: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? Jun 3, 2012 at 16:20
  • 1
    Here's a link to a way to do it without any dependencies, using JAXP: stackoverflow.com/questions/27222992/…
    – bvdb
    Jun 12, 2015 at 16:08
  • 27
    I love SO's closed questions that have such very high visibility... Something went wrong somewhere if such a useful question was closed.
    – Dariusz
    May 9, 2017 at 7:18
  • 4
    i think 90% of the most useful questions are "Closed-off topic"..smh
    – Jeryl Cook
    Nov 12, 2017 at 14:26

6 Answers 6

214

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"
}}
11
  • 14
    Warning: The json.org.XML package does not exist in Android! Nov 25, 2011 at 14:49
  • 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? Jun 3, 2012 at 16:15
  • 2
    download all the files not just XML.java. From here: github.com/douglascrockford/JSON-java/downloads
    – Spiff
    Oct 18, 2012 at 15:37
  • 4
    What if you have a <test attrib="moretest" content="foo">bar</test>?
    – wchargin
    Jun 7, 2013 at 2:34
  • 1
    NOTE: 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
63

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);
4
  • 6
    + for maven dependency provided
    – zacheusz
    Jun 9, 2015 at 5:15
  • 2
    use the version of json mentioned in the post if you are on java 7 as latest version throws weird errors.
    – urug
    Oct 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
32

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

11
  • 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" } } ] }
    – Marcus
    Jun 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'.
    – Marcus
    Jun 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
4

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());
}
3

I have uploaded the project you can directly open in eclipse and run that's all https://github.com/pareshmutha/XMLToJsonConverterUsingJAVA

Thank You

1
2

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.