Convert XML to JSON in java

Project Structure






















XmlToJson.java

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

public class XmlToJson {

 public static void main(String[] args) 
 {
  String finRespXml = "<test attrib=\"moretest\" content=\"foo\">bar</test>";
  //String finRespXml = "<name>Rahul</name>";
  JSONObject xmlJSONObj;
  try 
  {
   xmlJSONObj = XML.toJSONObject(finRespXml);
   String jsonPrettyPrintString = xmlJSONObj.toString(10); // json reponse in 10 lines
         System.out.println(jsonPrettyPrintString);
  } catch (JSONException e) 
  {   
   e.printStackTrace();
  }
        

 }

}



Output:

{"test": {
          "content": [
                    "foo",
                    "bar"
          ],
          "attrib": "moretest"
}}


No comments:

Post a Comment