188

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! Commented 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? Commented 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/… Commented Jun 12, 2015 at 16:08
  • 28
    I love SO's closed questions that have such very high visibility... Something went wrong somewhere if such a useful question was closed. Commented May 9, 2017 at 7:18
  • 5
    i think 90% of the most useful questions are "Closed-off topic"..smh Commented Nov 12, 2017 at 14:26

6 Answers 6

217

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"
}}
Sign up to request clarification or add additional context in comments.

12 Comments

Warning: The json.org.XML package does not exist in Android!
@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?
download all the files not just XML.java. From here: github.com/douglascrockford/JSON-java/downloads
What if you have a <test attrib="moretest" content="foo">bar</test>?
NOTE: org.json's XML.toJSONObject() also correctly converts xml lists to json arrays (unlike jackson's XmlMapper which by default silently swallows).
|
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 Comments

+ for maven dependency provided
use the version of json mentioned in the post if you are on java 7 as latest version throws weird errors.
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
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.
34

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 Comments

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
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" } } ] }
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.
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'.
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.
|
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());
}

Comments

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 Comment

In case anyone needed an online tool here's one json2csharp.com/xml-to-java
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.