首页 > 解决方案 > 使用 volley 解析 json 时遇到问题

问题描述

我正在尝试使用 volley lib 从 flickr API 获取数据。

这是我的 json :

{
  "photos": {
    "page": 1,
    "pages": 48,
    "perpage": 100,
    "total": "4793",
    "photo": [
      {
        *"id": "48955365182",
        "owner": "49191827@N00",
        *"secret": "fd5e5fd91c",
        *"server": "65535",
       * "farm": 66,
        "title": "permitted burn. thermal, ca. 2019.",
        "ispublic": 1,
        "isfriend": 0,
        "isfamily": 0
      }, ...
   }
}

我正在尝试使用“ * ”获取字段:


private void parseJson() {

    String URL = "https://www.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=x&user_id=49191827%40N00&extras=&format=json&nojsoncallback=1";

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    JSONArray jsonArray ;
                    try {
                        jsonArray = response.getJSONArray("photo");
                        for(int i=0; i<jsonArray.length(); i++){
                            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                            Log.d("GGG",jsonObject.getString("secret"));
                            Log.d("GGG",jsonObject.getString("id"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.d("VVV",e.getMessage());
                    }


                }
            }, new Response.ErrorListener() {

            }
        }
    );
}

标签: javaandroidjsonandroid-volley

解决方案


您需要从最顶层的对象解析

jsonArray = response.getJSONObject("photos").getJSONArray("photo")

推荐阅读