首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android JSON 陣列解析實戰:JSONObject/JSONArray 逐層解析豆瓣圖書 API 回應

     編輯:程式設計綜合問答

豆瓣圖書 API 回傳包含 `books` 陣列的 JSON,每本書含 `publisher`、`image`、`title`、`author` (陣列)。使用 Android 內建 `org.json` 庫 (無需 Gson) 逐層解析完整流程。

原始 JSON 結構


{
  "count": 5,
  "start": 0,
  "total": 6736,
  "books": [
    {
      "publisher": "中國電力出版社",
      "image": "https://img3.douban.com/mpic/s1957104.jpg",
      "title": "Java Enterprise最佳實踐",
      "author": ["The OReilly Java Authors"]
    },
    {
      "publisher": "北京大學出版社",
      "image": "https://img5.douban.com/mpic/s1022519.jpg",
      "title": "Java應用程序設計接口(下冊)",
      "author": ["(美)James Gosling", "Frank Yellin", "Java 小組"]
    }
  ]
}

完整解析代碼 (含異常處理、型別安全)


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

public class BookParser {
    private static final String TAG = "BookParser";

    public static void parseBooksJson(String jsonStr) {
        try {
            // 1. 最外層 JSONObject
            JSONObject root = new JSONObject(jsonStr);

            // 2. 取得 books JSONArray
            JSONArray booksArray = root.getJSONArray("books");
            int count = booksArray.length();

            // 3. 逐項解析
            for (int i = 0; i < count; i++) {
                JSONObject book = booksArray.getJSONObject(i);

                // 基本欄位 (字串)
                String publisher = book.optString("publisher", "未知出版社");
                String imageUrl = book.optString("image", "");
                String title = book.optString("title", "無標題");

                // author 是 JSONArray,需轉為字串或 List
                JSONArray authorArray = book.optJSONArray("author");
                String authors = "佚名";
                if (authorArray != null && authorArray.length() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < authorArray.length(); j++) {
                        if (j > 0) sb.append(", ");
                        sb.append(authorArray.optString(j, ""));
                    }
                    authors = sb.toString();
                }

                // 4. 組裝資料模型 / 直接使用
                Log.d(TAG, String.format("書名: %s | 作者: %s | 出版社: %s | 圖片: %s",
                        title, authors, publisher, imageUrl));

                // 實際專案建議映射到 Book POJO
                // Book bookObj = new Book(title, authors, publisher, imageUrl);
            }

        } catch (JSONException e) {
            Log.e(TAG, "JSON 解析失敗", e);
            // 可在此上報崩潰分析平台
        }
    }
}

關鍵 API 對照表

需求方法說明
取得 JSONObjectgetJSONObject(key) / optJSONObject(key)opt 版本不拋異常,回傳 null
取得 JSONArraygetJSONArray(key) / optJSONArray(key)同上
取得字串getString(key) / optString(key, default)opt 版本提供預設值
取得整數getInt(key) / optInt(key, default)
取得布林getBoolean(key) / optBoolean(key, default)
檢查鍵是否存在has(key) / isNull(key)

常見錯誤避坑

  • ❌ 直接 `getString("author")` → **拋 JSONException**,因 author 是陣列。**必須先 `getJSONArray` 再迭代**。
  • ❌ 忽略 `opt` 系列方法 → 缺欄位直接崩潰。**生產環境一律用 `optXxx` + 預設值**。
  • ❌ 大量資料在主執行緒解析 → ANR。**放入 Worker/RxJava/Coroutine 背景執行緒**。
  • ❌ 手動拼接 JSON 字串測試 → 易出現逸出錯誤。**用線上 JSON 驗證器 (jsonlint.com) 驗證後再貼入代碼**。

進階:映射到 POJO (配合 Gson 更簡潔)


// 若專案已引入 Gson,兩行搞定
Gson gson = new Gson();
BookResponse response = gson.fromJson(jsonStr, BookResponse.class);
// BookResponse 含 List books; Book 含 List author;

總結

Android 內建 `org.json` 解析巢狀 JSON 陣列:**`JSONObject` → `getJSONArray` → 迴圈 `getJSONObject` → `optString`/`optJSONArray` 取值**。嚴守「用 opt 系列防崩潰、背景執行緒防 ANR、POJO 映射提可讀性」三原則,即可穩健處理各類 API 回應。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved