Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

如何刪除與更新 JSONArray 中的指定項目

編輯:Android 開發教學

先假設手上有一個 JSONArray:

JSONArray Array1;

下面的程式碼以 name 為條件篩選,把不符合的項目放進新的 JSONArray,達到刪除的效果:

JSONArray newItems = new JSONArray();
String name = null;
try {
    name = orderDish.getString("name");
    JSONObject odItems = null;
    for (int j = 0; j < Array1.length(); j++) {
        odItems = (JSONObject) Array1.get(j);
        if (name.equals(odItems.getString("name"))) {
            Array1.put(j, null);   // 命中條件的設為 null
        } else {
            newItems.put(odItems); // 其餘的收進新陣列
        }
    }
} catch (JSONException e) {
    e.printStackTrace();
}

要替換的話,把符合條件的元素直接 put 成新的 JSONObject 即可。

兩個實務提醒

第一,JSONArray 並沒有真正的 remove 方法(早期版本),put(j, null) 只是把該位置設為 null,length 不變,序列化後會出現 null 元素。若需要真正移除,用上面的「撿出法」重新組一個陣列會乾淨得多;API 19 之後才有 remove(int index)。

第二,在迴圈中邊遍歷邊改動同一個集合是常見的錯誤來源。上面的寫法之所以安全,是因為改的是「值」而非「結構」;一旦改用 remove,索引會整體前移,很容易漏掉項目。這種情況下應該倒序遍歷,或先收集要刪的索引再統一處理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved