java - 为什么我的代码从嵌套的 JSON 数组返回值 'null'

标签 java android json api android-volley

所以我正在尝试获取“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();
}

enter image description here

最佳答案

您有 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/

相关文章:

java - 获取空查询结果后的列名称

java - 当使用率低于 MaxHeapFreeRatio 时,为什么分配的堆内存没有缩减?

javascript - 将回调/函数从 native 发送到 javascript

json - 扩展 Magento 中的当前 API 以获取 JSON 格式的项目

java - 无法解决依赖项版本冲突(NoSuchMethodError's)

java - 在 Java 中解析具有多个定界符的字符串

当 URI 设置为数据源时,Android 不播放歌曲

android - 布局中的布局 <layout> 在基本布局文件夹中没有声明 [错误]

javascript - 当数组中存在具有特定值的键时如何使用 ng-show ?

javascript - 如何将 json 对象与字符串进行比较?