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

How Can I Quickly Convert XML to JSON in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 03:26:11649browse

How Can I Quickly Convert XML to JSON in Java?

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:

  1. Add the Maven dependency to your project:
<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20180813</version>
</dependency>
  1. Utilize the XML.java class:
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());
}
  1. Expected output:
{
    "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!

Statement:
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