代码之家  ›  专栏  ›  技术社区  ›  astric mobiles

为什么我的代码从嵌套的JSON数组返回值“null”

  •  1
  • astric mobiles  · 技术社区  · 8 年前

    因此,我试图获取“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();
    }
    

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  2
  •   soote    8 年前

    你有两个问题。

    1) 变量作用域不正确 statusSeverityDescription for循环一结束,变量就被释放。要解决此问题,请移动 String statusSeverityDescription

    String statusSeverityDescription;
    for (int j = 0; j < len; j++) {                                
       JSONObject o = arrayStatus.getJSONObject(j);
       statusSeverityDescription = o.optString(
                                            "statusSeverityDescription", "");
    }
    

    2) 应该是存储所有 状态严重性描述 在json负载中。因此,将其设置为一个数组,或者了解最后处理的 状态严重性描述 对于给定的 lineStatuses 将是 状态严重性描述 剩下的就是你了。