2016-02-26 171 views
0

使用下面的代碼來解析json對象內的json數組。解析json數組時出現超出範圍錯誤的索引

JSONObject notificationResponse = new JSONObject(response.toString()); 
JSONObject value = new JSONObject(notificationResponse.getString("value")); 
JSONArray details = value.optJSONArray("details"); 
final int numberOfItems = details.length(); 

for (int i =0; i <= numberOfItems; i++){ 
JSONObject jsonObjects = details.getJSONObject(i); 
String text = jsonObjects.getString("text"); 
String date = jsonObjects.getString("date & time"); 
Log.d(TAG,text + " " +date); 
    } 

} catch (Exception e) { 
     e.printStackTrace(); 
    } 

以下是我的json。

{"status":1,"value":{"details":[{"text":"sample", "date & time":"12-NOV-15 3:30pm"}]}} 

我的代碼out of range例外在JSONObject jsonObjects = details.getJSONObject(i);

+1

只需更換for循環<=與<僅 – Manifest

+1

除去等號條件 我

回答

1

試使用以下內容:

for (int i =0; i < numberOfItems; i++){ 
JSONObject jsonObjects = details.getJSONObject(i); 
String text = jsonObjects.getString("text"); 
String date = jsonObjects.getString("date & time"); 
Log.d(TAG,text + " " +date); 
} 
1

使用

for (int i =0; i < numberOfItems; i++) 
{ 
JSONObject jsonObjects = details.getJSONObject(i); 
String text = jsonObjects.getString("text"); 
String date = jsonObjects.getString("date & time"); 
Log.d(TAG,text + " " +date); 
} 

,而不是

for (int i =0; i <= numberOfItems; i++) 
    { 
    JSONObject jsonObjects = details.getJSONObject(i); 
    String text = jsonObjects.getString("text"); 
    String date = jsonObjects.getString("date & time"); 
    Log.d(TAG,text + " " +date); 
    } 
1

請試試這個 使用i < numberOfItems;代替i <= numberOfItems;

JSONObject notificationResponse = new JSONObject(response.toString()); 
JSONObject value = new JSONObject(notificationResponse.getString("value")); 
JSONArray details = value.optJSONArray("details"); 
final int numberOfItems = details.length(); 

for (int i =0; i < numberOfItems; i++){ 
JSONObject jsonObjects = details.getJSONObject(i); 
String text = jsonObjects.getString("text"); 
String date = jsonObjects.getString("date & time"); 
Log.d(TAG,text + " " +date); 
    } 

} catch (Exception e) { 
     e.printStackTrace(); 
    } 

希望這有助於你

1

刪除=從你的for循環

for (int i =0; i < numberOfItems; i++) 

JsonArray指數從0開始,所以length()將返回(總規模-1)

1

由於正在發起所述環爲I = 0由此條件應作如下修改:

for (int i =0; i < numberOfItems; i++){ 
} 

代替

for (int i =0; i <= numberOfItems; i++){ 
}