如何在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 生日广州男生祝福语简短