Converting XML to JSON in Java: Rapid Solutions
When working with XML and JSON data, it's often necessary to convert between the two formats. Java provides various tools to facilitate this conversion quickly and efficiently.
One of the recommended libraries for this task is JSON in Java. Here's how to use it:
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180813</version> </dependency>
import org.json.JSONObject; import org.json.XML; import org.json.JSONException; // ... // Sample XML string String testXmlString = "<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to JSON</test>"; try { // Convert XML to JSON JSONObject xmlJsonObj = XML.toJSONObject(testXmlString); // Pretty-print the JSON result String jsonPrettyPrintString = xmlJsonObj.toString(PRETTY_PRINT_INDENT_FACTOR); System.out.println(jsonPrettyPrintString); } catch (JSONException je) { System.out.println(je.toString()); }
{ "test": { "attrib": "moretest", "content": "Turn this to JSON" } }
This solution allows you to efficiently convert XML to JSON in Java, with customizable formatting options for improved readability.
The above is the detailed content of How Can I Quickly Convert XML to JSON in Java?. For more information, please follow other related articles on the PHP Chinese website!