如何在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 给司机老师祝福语简短