开发者

how do I traverse an android JSONArray witin a JSONObject

I have a JSONObject with the data structure as follows

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

and I'm trying to traverse each array within that object, I have the following code where locationArray is the valid 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_开发者_如何学JAVAid");
}

but i'm getting an error trying to find each sub array of locationArray with an integer.


the solution:

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");
}

There is an error in your code. j_obj = locationArray.getJSONArray(j); should be j_obj = locationArray.getJSONObject(j);, as the object wrapped with curly braces represents a JSONObject and not a JSONArray

Edit: you may consider using obj.optString("location_id"); to avoid a potential problem

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜