如何在 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"
    }
]}}

更新日期:2020 年 7 月 4 日

7K+ 次觀看

開啟你的職業生涯

完成課程後即可獲得認證

開始學習
廣告