如何在 Java 中将 XML 转换为 JSON 数组?
javajsonobject oriented programmingprogramming更新于 2025/7/6 15:08:17
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\">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"
}
]}}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

