简体   繁体   English

如何在JSONObject中遍历android JSONArray

[英]how do I traverse an android JSONArray witin a JSONObject

I have a JSONObject with the data structure as follows 我有一个JSONObject,数据结构如下

[{"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 我试图遍历该对象中的每个数组,我有以下代码,其中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");
}

but i'm getting an error trying to find each sub array of locationArray with an integer. 但我在尝试使用整数查找locationArray的每个子数组时遇到错误。

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); 应该是j_obj = locationArray.getJSONObject(j); , as the object wrapped with curly braces represents a JSONObject and not a JSONArray ,因为用花括号包裹的对象表示JSONObject而不是JSONArray

Edit: you may consider using obj.optString("location_id"); 编辑:您可以考虑使用obj.optString("location_id"); to avoid a potential problem 避免潜在的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM