Json从JsonArray获得JsonArray

时间:2016-10-26 21:36:17

标签: android json list

我有以下Json。 link

我希望获得image_hall_listimage_place_list所有url值 我尝试使用以下代码,但没有任何结果。

JSONObject JO = new JSONObject(result);
JSONArray ja = JO.getJSONArray("image_place_list"); //get the array

 for (int i = 0; i < ja.length(); i++) {
    JSONObject jo = null;
    try {
        jo = ja.getJSONObject(i);                    
        jsonurl.add(jo.getString("url"));
    } catch (JSONException e1) {
        e1.printStackTrace();
    }
}

3 个答案:

答案 0 :(得分:2)

试试这个:

JSONObject JO = new JSONObject(result);
JSONArray ja = JO.getJSONArray("place_list"); //get the array
for (int i = 0; i < ja.length(); i++) {
    JSONObject jo = null;
    try {
        jo = ja.getJSONObject(i);
        JSONArray imageHallList = jo.getJSONArray("image_hall_list");
        for (int j = 0; j < imageHallList.length(); j++) {
            JSONObject oneImageHallList = imageHallList.getJSONObject(j);
            jsonurl.add(oneImageHallList.getString("url"));
        }
        JSONArray imagePlaceList = jo.getJSONArray("image_place_list");
        for (int j = 0; j < imagePlaceList.length(); j++) {
            JSONObject oneImagePlaceList = imagePlaceList.getJSONObject(j);
            jsonurl.add(oneImagePlaceList.getString("url"));
        }
    } catch (JSONException e1) {
        e1.printStackTrace();
    }
}

答案 1 :(得分:1)

我会推荐一些方法。

提取给定对象的所有URL。

public ArrayList<String> getURLs(JSONObject jo, String key) throws JSONException {
    List<String> urls = new ArrayList<String>();
    JSONArray arr = jo.getJSONArray(key);
    for (int j = 0; j < arr.length(); j++) {
        JSONObject innerObj = arr.getJSONObject(j);
        urls.add(innerObj.getString("url"));
    }
    return urls;
}

然后,您可以使用两次相应的键。如果您的"place_list"变量直接来自该链接,您还需要首先获得result

try {
    JSONObject jsonResponse = new JSONObject(result);
    JSONArray ja = jsonResponse.getJSONArray("place_list"); //get the array

     for (int i = 0; i < ja.length(); i++) {
        JSONObject jo = ja.getJSONObject(i);                    
        jsonurl.addAll(getURLs(jo, "image_hall_list"));
        jsonurl.addAll(getURLs(jo, "image_place_list"));
    }
} catch (JSONException e1) {
    e1.printStackTrace();
}

答案 2 :(得分:0)

使用嵌套的for循环。首先抓住image_hall_listimage_place_list之前的项目,然后在存储了值后,通过获取该JSON对象并循环遍历image_hall_listimage_place_list。 JSON对象中的元素。