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

How to convert XML to JSON array in Java?

PHPz
PHPzforward
2023-09-14 23:01:021272browse

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

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

Output

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete