📜  org.json-XML(1)

📅  最后修改于: 2023-12-03 15:18:10.439000             🧑  作者: Mango

org.json-XML

Introduction

org.json-XML is a Java library that converts JSON data to and from XML format. It provides a simple and efficient way to convert data between these two formats with a few lines of code.

Features

The main features of org.json-XML library are:

  • Converts JSON data to XML and vice versa.
  • No dependencies on external libraries.
  • Supports XML attributes, CDATA sections, and comments.
  • Provides options to control the conversion process.
  • Handles invalid JSON and XML data gracefully.
Installation

You can download the library from the following URL:

https://mvnrepository.com/artifact/org.json/json

Alternatively, you can add a Maven dependency in your project:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>
Usage

Here's a simple example that shows how to convert JSON data to XML:

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

public class Main {
    public static void main(String[] args) {
        String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
        JSONObject jsonObject = new JSONObject(json);
        String xml = XML.toString(jsonObject);
        System.out.println(xml);
    }
}

Output:

<root>
  <name>John</name>
  <age>30</age>
  <city>New York</city>
</root>

Similarly, you can convert XML data to JSON with the following code:

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

public class Main {
    public static void main(String[] args) {
        String xml = "<root><name>John</name><age>30</age><city>New York</city></root>";
        JSONObject jsonObject = XML.toJSONObject(xml);
        String json = jsonObject.toString();
        System.out.println(json);
    }
}

Output:

{"root":{"name":"John","age":30,"city":"New York"}}

You can also provide various options to control the conversion process. For example, you can set the indent factor, whether to include XML declaration, etc.:

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

public class Main {
    public static void main(String[] args) {
        String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
        JSONObject jsonObject = new JSONObject(json);
        String xml = XML.toString(jsonObject, "person", true, null, 4);
        System.out.println(xml);
    }
}

Output:

<?xml version="1.0" encoding="UTF-8"?>
<person>
    <name>John</name>
    <age>30</age>
    <city>New York</city>
</person>
Conclusion

org.json-XML library provides a straightforward way to convert JSON data to XML and vice versa. It is a lightweight and flexible library that can handle a variety of data formats, making it suitable for many different applications.