JSON 中 playlists 字段的 Key 為動態 ID(\"10063\", \"10157\"),無法直接用固定 Key 獲取。需用 JSONObject.keys() 獲取迭代器遍歷所有 Key。
JSONObject playlists = json.getJSONObject("playlists");
Iterator keys = playlists.keys();
while (keys.hasNext()) {
String playlistId = keys.next();
JSONObject playlist = playlists.getJSONObject(playlistId);
String id = playlist.getString("id");
String name = playlist.getString("name");
JSONArray songs = playlist.getJSONArray("songs");
// 處理 id, name, songs
Log.d("Playlist", "ID: " + id + ", Name: " + name + ", Songs: " + songs.length());
}
動態 Key 作為對象屬性名不利於解析,建議服務端返回數組格式:
"playlists": [
{"id": "10063", "name": "Favorites", "songs": [...]},
{"id": "10157", "name": "80s", "songs": [...]}
]
客戶端即可直接 getJSONArray(\"playlists\") 遍歷,無需反射式 Key 迭代。
keys() 迭代是唯一方式。keys() 返回順序不固定,業務邏輯不應依賴順序。動態 Key 用 keys() 迭代,推薦服務端改數組結構簡化客戶端。