豆瓣圖書 API 回傳包含 `books` 陣列的 JSON,每本書含 `publisher`、`image`、`title`、`author` (陣列)。使用 Android 內建 `org.json` 庫 (無需 Gson) 逐層解析完整流程。
{
"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);
// 可在此上報崩潰分析平台
}
}
}
| 需求 | 方法 | 說明 |
|---|---|---|
| 取得 JSONObject | getJSONObject(key) / optJSONObject(key) | opt 版本不拋異常,回傳 null |
| 取得 JSONArray | getJSONArray(key) / optJSONArray(key) | 同上 |
| 取得字串 | getString(key) / optString(key, default) | opt 版本提供預設值 |
| 取得整數 | getInt(key) / optInt(key, default) | |
| 取得布林 | getBoolean(key) / optBoolean(key, default) | |
| 檢查鍵是否存在 | has(key) / isNull(key) |
// 若專案已引入 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 回應。