Android,无法在 for 循环内迭代 JSONArray
Android, cannot iterate through JSONArray inside for-loop
我正在尝试以下操作来遍历 JSONArray 中的每个 JSONObject,但它不起作用。我检查了日志中 JSONArray 的长度,它给出了正确的长度,但我无法在 JSONArray 的每个元素处获取 JSONObject。此外,每个元素都应该是一个包含 8 key/value 对的 JSONObject。非常感谢任何反馈,谢谢。
if (getMyJSONArray() != null) {
newJSONArray = getMyJSONArray();
try {
// Did this because the JSONArray was inside a JSONArray
innerJSONArray = newJSONArray.getJSONArray(0);
} catch (JSONException e) {
e.printStackTrace();
}
if (innerJSONArray != null) {
// This gives me the right length
Log.i("innerJSONArray.length: ", String.valueOf(innerJSONArray.length()));
for (int i = 0; innerJSONArray.length() < 0; i++) {
try {
// This doesn't work
JSONObject jsonObject1 = innerJSONArray.getJSONObject(i);
// This doesn't work either
JSONObject jsonObject2 = new JSONObject(innerJSONArray.getString(i));
…(more code below to use if the part above works)
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
在你的 for 循环中 innerJSONArray.length() < 0;
应该是 i < innerJSONArray.length()
.
那么这一行应该按预期工作:
JSONObject jsonObject1 = innerJSONArray.getJSONObject(i);
我正在尝试以下操作来遍历 JSONArray 中的每个 JSONObject,但它不起作用。我检查了日志中 JSONArray 的长度,它给出了正确的长度,但我无法在 JSONArray 的每个元素处获取 JSONObject。此外,每个元素都应该是一个包含 8 key/value 对的 JSONObject。非常感谢任何反馈,谢谢。
if (getMyJSONArray() != null) {
newJSONArray = getMyJSONArray();
try {
// Did this because the JSONArray was inside a JSONArray
innerJSONArray = newJSONArray.getJSONArray(0);
} catch (JSONException e) {
e.printStackTrace();
}
if (innerJSONArray != null) {
// This gives me the right length
Log.i("innerJSONArray.length: ", String.valueOf(innerJSONArray.length()));
for (int i = 0; innerJSONArray.length() < 0; i++) {
try {
// This doesn't work
JSONObject jsonObject1 = innerJSONArray.getJSONObject(i);
// This doesn't work either
JSONObject jsonObject2 = new JSONObject(innerJSONArray.getString(i));
…(more code below to use if the part above works)
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
在你的 for 循环中 innerJSONArray.length() < 0;
应该是 i < innerJSONArray.length()
.
那么这一行应该按预期工作:
JSONObject jsonObject1 = innerJSONArray.getJSONObject(i);