如何在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= "<?xml version=\"1.0\" ?><root><test attrib=\"jsontext1\">nhooo</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": "nhooo"
},
{
"attrib": "jsontext2",
"content": "tutorix"
}
]}}热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特