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
}
}
JSONArray.fromObject() 把字串解析為陣列結構。JSONArray.toCollection() 轉成 Collection,方便用 Iterator 走訪。JSONObject.toBean(json, Test.class) 對應到具體的 JavaBean。使用 json-lib 時,套件可自 SourceForge 的 json-lib 專案頁取得。除了 json-lib,常見的替代方案還有 Jackson、Gson 與 fastjson,其中 Jackson 的 ObjectMapper.readValue(str, new TypeReference<List<Test>>(){}) 一行就能完成整個清單轉換,不必手動迴圈。