Converting XML to JSON in Java: A Swift Solution
Finding the most efficient approach to convert XML to JSON in Java can be crucial for data integration and processing. Among the myriad of tools available, "JSON in Java" stands out for its effectiveness.
Leveraging JSON in Java
JSON in Java provides a dedicated class, XML.java, designed for seamless XML to JSON conversion. By incorporating the provided Maven dependency:
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180813</version> </dependency>
you gain access to XML.java's transformational capabilities.
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
The toJSONObject method takes an XML string input (TEST_XML_STRING) and returns a corresponding JSON object. You can further enhance readability by configuring the indentation factor with the constant PRETTY_PRINT_INDENT_FACTOR.
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
The output will be a well-formatted JSON string, ready for consumption. For instance, converting the XML string:
<?xml version="1.0" ?> <test attrib="moretest">Turn this to JSON</test>
will produce the following JSON string:
{ "test": { "attrib": "moretest", "content": "Turn this to JSON" } }
Utilizing JSON in Java offers a swift and reliable solution for converting XML to JSON in your Java applications.
The above is the detailed content of How Can I Efficiently Convert XML to JSON in Java?. For more information, please follow other related articles on the PHP Chinese website!