Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

xml

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

like image 820
BeachRunnerFred Avatar asked Dec 01 '09 00:12

BeachRunnerFred


People also ask

Can we convert XML to JSON in Java?

We can convert XML to JSON array using org. json. XML class, this provides a static method, XML. toJSONObject() to convert XML to JSON array.

How JSON is faster than XML?

JSON is faster because it is designed specifically for data interchange. JSON encoding is terse, which requires less bytes for transit. JSON parsers are less complex, which requires less processing time and memory overhead. XML is slower, because it is designed for a lot more than just data interchange.


2 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" }} 
like image 141
danieltalsky Avatar answered Sep 19 '22 15:09

danieltalsky


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); 
like image 20
Kishan Bheemajiyani Avatar answered Sep 20 '22 15:09

Kishan Bheemajiyani