Home > Java > javaTutorial > How to convert XML to JSON array in Java?

How to convert XML to JSON array in Java?

PHPz
Release: 2023-09-14 23:01:02
forward
1283 people have browsed it

How to convert XML to JSON array in Java?

JSON is a lightweight data exchange format. The format of JSON is similar to key-value pairs. We can use the org.json.XML class to convert XML to a JSON array, which provides a static method, XML.toJSONObject() Convert XML to JSON array.

Syntax

public static JSONObject toJSONObject(java.lang.String string) throws JSONException
Copy after login

In the example below, Convert XML to JSON array

Example

import org.json.*;
public class ConvertXMLToJSONArrayTest {
   public static String xmlString= <strong>"<!--?xml version="1.0" ?--></strong><?xml version=\"1.0\" ?><root><test       attrib=\"jsontext1\">tutorialspoint</test><test attrib=\"jsontext2\">tutorix</test></root>";
   public static void main(String[] args) {
      try {
         JSONObject json = XML.toJSONObject(xmlString); // converts xml to json
         String jsonPrettyPrintString = json.toString(4); // json pretty print
         System.out.println(jsonPrettyPrintString);
      } catch(JSONException je) {
         System.out.println(je.toString());
      }
   }
}
Copy after login

Output

{"root": {"test": [
    {
    "attrib": "jsontext1",
    "content": "tutorialspoint"
    },
    {
    "attrib": "jsontext2",
    "content": "tutorix"
    }
]}}
Copy after login

The above is the detailed content of How to convert XML to JSON array in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template