所以我正在尝试获取“lineStatus”中的“statusSeveretyDescription”。第一个“for”循环有效,但是,嵌套循环返回空值。将不胜感激指向正确方向的指针。请查看下面的代码和 JSON 图像。
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.optJSONObject(i);
String line = object.optString("id");
//nested array
JSONArray arrayStatus = object.getJSONArray("lineStatuses");
int len = arrayStatus.length();
for (int j = 0; j < len; j++) {
JSONObject o = arrayStatus.getJSONObject(j);
String statusSeverityDescription = o.optString(
"statusSeverityDescription", "");
}
if (line != null) {
tubeLines.add(line + statusSeverityDescription);
}
// Once we added the string to the array, we notify the arrayAdapter
arrayAdapter.notifyDataSetChanged();
}
最佳答案
您有 2 个问题。
1) 您的变量作用域不正确,您的 statusSeverityDescription
变量在 for 循环结束后立即被释放。要解决此问题,请将 String statusSeverityDescription
移到 for 循环之外,就像这样
String statusSeverityDescription;
for (int j = 0; j < len; j++) {
JSONObject o = arrayStatus.getJSONObject(j);
statusSeverityDescription = o.optString(
"statusSeverityDescription", "");
}
2) statusSeverityDescription
应该是一个数组,它将所有 statusSeverityDescription
存储在您的 json 负载中。因此,将其设为一个数组,或者了解给定 lineStatuses
的最后处理的 statusSeverityDescription
将是您剩下的 statusSeverityDescription
。
关于java - 为什么我的代码从嵌套的 JSON 数组返回值 'null',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47064081/