2016-02-26 173 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++){ 
}