Home >Java >javaTutorial >How Can I Efficiently Convert XML to JSON in Java Using org.json?

How Can I Efficiently Convert XML to JSON in Java Using org.json?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-10 00:37:09782browse

How Can I Efficiently Convert XML to JSON in Java Using org.json?

How to Convert XML to JSON Quickly and Efficiently in Java

Introduction

Converting XML to JSON is a common data manipulation task in Java applications. This article explores various tools that facilitate this conversion process swiftly and effectively.

org.json: A Comprehensive Solution

The org.json library offers robust functionality for converting XML to JSON. It includes a dedicated XML class that handles this conversion task seamlessly.

Usage

Integrating org.json into your Java project is straightforward through the Maven dependency:

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20180813</version>
</dependency>

Once the dependency is configured, you can utilize the XML class to convert XML strings to JSON objects:

import org.json.JSONObject;
import org.json.XML;
import org.json.JSONException;

public class Main {

    ...

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

The above code converts the TEST_XML_STRING XML string into a JSON object and prints its pretty-printed representation. The output will be a nested JSON object that preserves the structure and attributes of the original XML.

Conclusion

The org.json library provides a simple and efficient means to convert XML to JSON in Java. Its intuitive API allows for quick and reliable data conversion, making it an invaluable tool for various data processing tasks.

The above is the detailed content of How Can I Efficiently Convert XML to JSON in Java Using org.json?. 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