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.


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

In the below example, converting XML to JSON array


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
      } catch(JSONException je) {


{"root": {"test": [
    "attrib": "jsontext1",
    "content": "tutorialspoint"
    "attrib": "jsontext2",
    "content": "tutorix"
Published on 24-Sep-2019 15:15:21