如何在 Java 中将 XML 转换为 JSON 数组?
JSON 是一种轻量级的数据交换格式,JSON 的格式就像一个键值对。我们可以利用org.json.XML 类将XML 转换为 JSON 数组,org.json.XML 类提供了一个静态方法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\">tutorialspoint</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": "tutorialspoint"
},
{
"attrib": "jsontext2",
"content": "tutorix"
}
]}}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP