如何使用Volley获取和解析JSON对象

时间:2015-11-25 22:46:11

标签: android android-volley

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

我正在尝试设置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对象?但是我如何访问和解析呢?

3 个答案:

答案 0 :(得分:11)

使用您的网址,您可以使用以下示例代码:

        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'

希望这有帮助!

答案 1 :(得分:0)

只需在浏览器上粘贴此网址,即可看到所有json对象。您可以使用json格式化程序网站以良好的格式查看。

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

您的代码无效,因为此json上不存在此对象。

答案 2 :(得分:0)

将GSON与简单的POJO一起使用。这是GSON Documentation

假设你有这个:

<paper-tabs id="mytabs" selected="0">
  <paper-tab>TAB 1</paper-tab>
  <paper-tab>TAB 2</paper-tab>
  <paper-tab>TAB 3</paper-tab>
</paper-tabs>

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

numbers=$( printf -v str '%s+' $@; printf '%s' "${str%+}" )
sum=$(( $numbers ))
echo $numbers=$sum 

现在你有一个代表响应的对象!请注意我是如何使“Song”对象的字段名称与您关注的值具有相同的名称(在这种情况下,它显示网络和站点是您想要的)。 Gson负责将JSON对象序列化为POJO,您可以直接轻松地访问值。

要转换回来,就像这样简单:

 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...
}

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

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