我使用以下代码来解析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);
例外情况
答案 0 :(得分: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 :(得分: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();
}
希望这有助于你
答案 2 :(得分:1)
remove =
for (int i =0; i < numberOfItems; i++ )
JsonArray
索引将从0开始,因此length()
将返回(总大小为1)
答案 3 :(得分: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);
}
答案 4 :(得分:1)
由于你是以 i = 0 开始循环,因此条件应修改如下:
for (int i =0; i < numberOfItems; i++ ){
}
而不是
for (int i =0; i <= numberOfItems; i++ ){
}