如何在 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