Home > Java > javaTutorial > How Can I Reliably Convert XML to JSON in Java?

How Can I Reliably Convert XML to JSON in Java?

Linda Hamilton
Release: 2024-12-29 17:09:11
Original
435 people have browsed it

How Can I Reliably Convert XML to JSON in Java?

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>
Copy after login

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());
        }
    }
}
Copy after login

Output:

{"test": {
    "attrib": "moretest",
    "content": "Turn this to JSON"
}}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template