我有一个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 的每个子数组时遇到错误。
最佳答案
解决方法:
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");
来避免潜在的问题
关于android - 我如何通过 JSONObject 遍历 android JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4471322/