【问题标题】:how do I traverse an android JSONArray witin a JSONObject如何在 JSONObject 中遍历 android JSONArray
【发布时间】:2011-05-27 03:49:10
【问题描述】:

我有一个JSONObject,其数据结构如下

[{"distance":"200 meters","location_id":"519"},{"distance":"300 meters","location_id":"219"}]

我正在尝试遍历该对象中的每个数组,我有以下代码,其中 locationArray 是有效的 JSONObject

for (int j = 0; j < locationArray.length(); j++) {

     JSONObject j_obj;
     j_obj = locationArray.getJSONArray(j); //error here
     location_id = j_obj.getString("location_id");
}

但我在尝试使用整数查找 locationArray 的每个子数组时遇到错误。

【问题讨论】:

    标签: android arrays json multidimensional-array


    【解决方案1】:

    解决办法:

    JSONArray rootArray = new JSONArray(jsonString);
    int len = rootArray.length();
    for(int i = 0; i < len; ++i) {
        JSONObject obj = rootArray.getJSONObject(i);
        location_id = obj.getString("location_id");
    }
    

    您的代码中有错误。 j_obj = locationArray.getJSONArray(j); 应该是 j_obj = locationArray.getJSONObject(j);,因为用花括号包裹的对象代表 JSONObject 而不是 JSONArray

    编辑:您可以考虑使用obj.optString("location_id"); 来避免潜在问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 2016-07-22
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多