Search code examples
javajsonxmlstax

Efficient parser to convert XML to JSON in java without JsonObject and Array


I tried to convert XML to JSON in java. I am using Stax parser for Conversion. After getting START_ELEMENT, END_ELEMENT, CHARACTERS, I don't know how to convert it to JSON Format. Not use any inbuilt libraries, JsonObject, JSonArray.IS any logic available For this conversion...


Solution

  • Sample code to convert XML to JSON. Create a java project in eclipse since I am creating a java project I will manually import the Java-json.jar by right-clicking on the project and select configure build path their by selecting the add external jar option add the jar file and run the project. If you are building using maven project add the following dependency in the pom.xml

    <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
    

    package com.test.jsontoxml
    import org.json.JSONException;
    import org.json.JSONObject;
    import org.json.XML;
    
    public class JsonConversion {
    
     public static int PRETTY_PRINT_INDENT_FACTOR = 4;
        public static String TEST_XML_STRING =
            "<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to JSON</test>";
    
        public static void main(String[] args) {
            try {
                JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
                String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
                System.out.println(jsonPrettyPrintString);
            } catch (JSONException je) {
                System.out.println(je.toString());
            }
        }
    }