How to get and parse a JSON-object with Volley

With your Url, you can use the following sample code:

        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);

The SongInfo 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;
}

Inside build.gradle file:

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

Hope this helps!

Leave a Comment