Home » Android » android – How to get and parse a JSON-object with Volley

android – How to get and parse a JSON-object with Volley

Posted by: admin June 15, 2020 Leave a comment

Questions:

I haven’t been able to find a detailed answer to this question, or at least not one that I can understand.

I’m trying to set up Volley to pull down JSON-objects from iTunes. I then want to parse the objects, to get their image URLs.

So for example, here is am iTunes JSON object URL

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

So here I’ve set up my code to get this object (using a tutorial of course)

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

The very last statement is

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

Presumably, I now have the JSON-object? But how can I access and parse it?

How to&Answers:

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!

Answer:

Just paste this url on your browser, you can see all the json object. You can use a json formatter website to see in a nice format.

Take a look here to find the methods you need.
http://developer.android.com/reference/org/json/JSONObject.html

Your code is not working because this objects don’t exist on this json.

Answer:

Use GSON with simple POJO’s. Here is the GSON Documentation

Suppose you have this:

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

You can use GSON to do this:

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

And now you have an object representing the response! Notice how I made the field names of the “Song” object have the same names as the values you care about (in this case it appears network and site is what you wanted). Gson does the job of serializing a JSON object to a POJO that you can directly access values cleanly, and easier.

To convert back it is as simple as:

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

Just add to your build.gradle via:

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