0
你好,我有一個棘手的問題,我已經解決了幾個小時。Android從json數組中獲取內部的json數組
這是我的JSON響應:
{
"DATA": [
{
"Name": "Aha",
"ListData": [
{
"ID": 1
},
{
"ID": 2
},
{
"ID": 3
}
]
}
]
}
這是我到目前爲止已經完成:陣列的
try {
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonArray = jsonObj.getJSONArray("DATA");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
JSONArray arr = data.getJSONArray(Constants.LIST_DATA);
for(int j = 0; j < arr.length(); j++) {
JSONObject innerData = arr.getJSONObject(i);
int id = innerData.getInt(Constants.ID);
item = new HashMap<>();
item.put(Constants.ID, id);
itemList.add(item);
}
}
} catch(JSONException e) {
Log.e("JSONException", "" + e.toString());
}
但我只得到正確的大小(3),但我得到的是相同的ID,1.我的代碼有什麼問題?任何幫助將不勝感激。謝謝!
結果是這樣的:
ID=1,ID=1,ID=1
而我的預期是:
ID=1,ID=2,ID=3
你的id是int,所以用這段代碼讀取'''int id = innerData.getInt(Constants.ID);'''''arr.getJSONObject(j);''' – xxxzhi
JSONObject innerData = arr .getJSONObject(ⅰ);這是錯誤的用JSONObject替換innerData = arr.getJSONObject(j); –