Java XML to JSON Conversion Techniques
Seeking reliable methods to convert XML to JSON in Java? Here are effective solutions:
JSON in Java
JSON in Java offers valuable resources for converting XML to JSON. Maven dependency:
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180813</version> </dependency>
The XML.java class is crucial for this conversion:
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:
{"test": { "attrib": "moretest", "content": "Turn this to JSON" }}
The above is the detailed content of How Can I Reliably Convert XML to JSON in Java?. For more information, please follow other related articles on the PHP Chinese website!