Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

JSON 物件陣列轉 Java 物件:JSONArray 與 toBean 的實務用法

JSON 之所以在客戶端與伺服器之間流行,是因為它簡潔而好處理。但當傳輸的內容是「物件陣列」而非單一物件時,就需要多一道手續:先把 JSON 字串解析成 JSONArray,再逐項轉成 JavaBean。

轉換程式碼

JSONArray testJSONArray = JSONArray.fromObject(testArrayStr);
Collection testArray = JSONArray.toCollection(testJSONArray);

if (testArray != null && !testArray.isEmpty()) {
    Iterator it = testArray.iterator();
    while (it.hasNext()) {
        JSONObject testJSONObj = JSONObject.fromObject(it.next());
        Test test = (Test) JSONObject.toBean(testJSONObj, Test.class);
        // ... 在這裡處理 test
    }
}

流程拆解

  1. JSONArray.fromObject() 把字串解析為陣列結構。
  2. JSONArray.toCollection() 轉成 Collection,方便用 Iterator 走訪。
  3. 逐一以 JSONObject.toBean(json, Test.class) 對應到具體的 JavaBean。

使用 json-lib 時,套件可自 SourceForge 的 json-lib 專案頁取得。除了 json-lib,常見的替代方案還有 Jackson、Gson 與 fastjson,其中 Jackson 的 ObjectMapper.readValue(str, new TypeReference<List<Test>>(){}) 一行就能完成整個清單轉換,不必手動迴圈。

幾個實務提醒

  • 空值與型別:JSON 的數字在解析後可能變成 Integer、Long 或 Double,若 JavaBean 欄位型別與 JSON 值不一致,toBean 會靜默丟棄或填 null,最好先確認兩邊定義一致。
  • 欄位對應:json-lib 依名稱對應,因此 JSON 的 key 必須與 JavaBean 的屬性名相同,否則該欄位不會被填入。
  • 效能:逐筆 toBean 在大清單下會明顯變慢,若只讀取少數欄位,直接操作 JSONObject 反而更快。
  • 安全性:反序列化不可信的輸入時,應避免讓框架依輸入內容決定要例示化的類別,以降低反序列化攻擊的風險。
Copyright © Linux教程網 All Rights Reserved