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.
public static JSONObject toJSONObject(java.lang.String string) throws JSONException
In the example below, Convert XML to JSON array
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()); } } }
{"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!