如何使用 Volley 获取和解析 JSON-object

How to get and parse a JSON-object with Volley

我没能找到这个问题的详细答案,或者至少找不到我能理解的答案。

我正在尝试设置 Volley 以从 iTunes 中拉下 JSON-对象。然后我想解析对象,得到它们的图像 URLs.

例如,这里是 iTunes JSON 对象 URL

String url = "https://itunes.apple.com/search?term=michael+jackson";

所以我在这里设置了我的代码来获取这个对象(当然使用教程)

String url = "https://itunes.apple.com/search?term=michael+jackson";

JsonObjectRequest jsonRequest = new JsonObjectRequest
        (Request.Method.GET, url, null, new Downloader.Response.Listener // Cannot resolve symbol Listener
                <JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                // the response is already constructed as a JSONObject!
                try {
                    response = response.getJSONObject("args");
                    String site = response.getString("site"),
                            network = response.getString("network");
                    System.out.println("Site: "+site+"\nNetwork: "+network);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Downloader.Response.ErrorListener // Cannot resolve symbol ErrorListener
                () {

            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

Volley.newRequestQueue(this).add(jsonRequest);

最后一句话是

Volley.newRequestQueue(this).add(jsonRequest);

据推测,我现在有 JSON-对象?但是我怎样才能访问和解析它呢?

只需将此 url 粘贴到您的浏览器中,您就可以看到所有 json 对象。您可以使用 json 格式化程序网站以漂亮的格式查看。

看看这里找到你需要的方法。 http://developer.android.com/reference/org/json/JSONObject.html

您的代码无法正常工作,因为此 json 上不存在此对象。

将 GSON 与简单的 POJO 结合使用。这是 GSON Documentation

假设你有这个:

 public class Song{
     private String site;
     private String network;

     public void setSite(String site){
         this.site = site;
     }
     public void setNetwork(String network{
         this.network = network;
     }

     //Add getters as well...
}

您可以使用 GSON 来执行此操作:

Song song = Gson.fromJson(response.getJSONObject("args"), Song.class);

现在您有一个表示响应的对象!请注意我是如何使 "Song" 对象的字段名称与您关心的值具有相同名称的(在这种情况下,网络和站点似乎是您想要的)。 Gson 负责将 JSON 对象序列化为 POJO,这样您就可以干净利落地直接访问值。

转换回来很简单:

JSONObject obj = new JSONObject(gson.toJson(song));

只需通过以下方式添加到您的 build.gradle:

compile 'com.google.code.gson:gson:1.7.2'

根据您的 Url,您可以使用以下示例代码:

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = "https://itunes.apple.com/search?term=michael+jackson";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if (response != null) {
                    int resultCount = response.optInt("resultCount");
                    if (resultCount > 0) {
                        Gson gson = new Gson();
                        JSONArray jsonArray = response.optJSONArray("results");
                        if (jsonArray != null) {
                            SongInfo[] songs = gson.fromJson(jsonArray.toString(), SongInfo[].class);
                            if (songs != null && songs.length > 0) {
                                for (SongInfo song : songs) {
                                    Log.i("LOG", song.trackViewUrl);
                                }
                            }
                        }
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("LOG", error.toString());
            }
        });
        requestQueue.add(jsonObjectRequest);

歌曲信息class:

public class SongInfo {
    public String wrapperType;
    public String kind;
    public Integer artistId;
    public Integer collectionId;
    public Integer trackId;
    public String artistName;
    public String collectionName;
    public String trackName;
    public String collectionCensoredName;
    public String trackCensoredName;
    public String artistViewUrl;
    public String collectionViewUrl;
    public String trackViewUrl;
    public String previewUrl;
    public String artworkUrl30;
    public String artworkUrl60;
    public String artworkUrl100;
    public Float collectionPrice;
    public Float trackPrice;
    public String releaseDate;
    public String collectionExplicitness;
    public String trackExplicitness;
    public Integer discCount;
    public Integer discNumber;
    public Integer trackCount;
    public Integer trackNumber;
    public Integer trackTimeMillis;
    public String country;
    public String currency;
    public String primaryGenreName;
    public String radioStationUrl;
    public Boolean isStreamable;
}

在 build.gradle 文件中:

compile 'com.mcxiaoke.volley:library:1.0.19'
compile 'com.google.code.gson:gson:2.5'

希望对您有所帮助!