What are some good tools for quickly and easily converting 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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With