How to convert XML to JSON array in Java?

JavaJSONObject Oriented ProgrammingProgramming

A JSON is a lightweight data-interchange format and the format of JSON is like a key-value pair. We can convert XML to JSON array using org.json.XML class, this provides a static method, XML.toJSONObject() to convert XML to JSON array.

Syntax

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

In the below example, converting XML to JSON array

Example

import org.json.*;
public class ConvertXMLToJSONArrayTest {
   public static String xmlString= "<?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"
    }
]}}
raja
Published on 24-Sep-2019 15:15:21
Advertisements