如何在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 兄妹拍照祝福语简短的话