java xml转json数组_如何在Java中将XML转换为JSON数组?

JSON是轻量级的数据交换格式,JSON的格式类似于键值对。我们可以使用org.json.XML类将XML转换为JSON数组,这提供了一个静态方法XML.toJSONObject()来将XML转换为JSON数组。

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

在下面的示例中,将XML转换为JSON数组

示例import org.json.*;

public class ConvertXMLToJSONArrayTest {

public static String xmlString= "nhoootutorix";

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": "nhooo"

},

{

"attrib": "jsontext2",

"content": "tutorix"

}

]}}

你可能感兴趣的:(java,xml转json数组)