【问题标题】:How to get and parse a JSON-object with Volley如何使用 Volley 获取和解析 JSON 对象
【发布时间】:2015-11-25 22:46:10
【问题描述】:

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

我正在尝试设置 Volley 以从 iTunes 中提取 JSON 对象。然后我想解析对象,以获取它们的图像 URL。

例如,这里是 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 对象?但是如何访问和解析呢?

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

    通过您的 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);
    

    SongInfo 类:

    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'
    

    希望这会有所帮助!

    【讨论】:

    • 确实有帮助!非常感谢。
    【解决方案2】:

    只要把这个 url 粘贴到你的浏览器上,你就可以看到所有的 json 对象。您可以使用 json formatter 网站以很好的格式查看。

    查看此处以找到您需要的方法。 http://developer.android.com/reference/org/json/JSONObject.html

    您的代码不起作用,因为此 json 中不存在此对象。

    【讨论】:

      【解决方案3】:

      将 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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-16
        • 1970-01-01
        • 1970-01-01
        • 2021-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多