[英]Why is my code returning value of 'null' from a nested JSON array
因此,我试图获取位于“ lineStatus”内的“ statusSeveretyDescription”。 第一个“ for”循环有效,但是嵌套循环返回null。朝正确方向的指针将不胜感激。 请在下面查看代码和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)您的变量作用域定义不正确,for循环结束后将立即释放statusSeverityDescription
变量。 要解决此问题,请将String statusSeverityDescription
移到for循环外,如下所示
String statusSeverityDescription;
for (int j = 0; j < len; j++) {
JSONObject o = arrayStatus.getJSONObject(j);
statusSeverityDescription = o.optString(
"statusSeverityDescription", "");
}
2) statusSeverityDescription
应该是一个数组,用于在json有效负载中存储所有statusSeverityDescription
。 因此,使它的阵列,或者明白,最后处理statusSeverityDescription
对于给定lineStatuses
将是statusSeverityDescription
你留下了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.