Reputation: 145
I am building a web application in which I want to display iTunes top 10 Songs and iTunes top 10 albums.
I have used https://rss.itunes.apple.com/ link to generate it and changed from XML to json.
http://itunes.apple.com/au/rss/topsongs/limit=10/json
I am getting JSON from the above link. And can view in JSON Viewer
http://jsonviewer.stack.hu/#http://itunes.apple.com/au/rss/topsongs/limit=10/json
However, I am confuse on how to read the JSON Object so that I can get the required fields. (entry > title)
I am able to get to the entry and loop through the array to get all the title. However I am not sure about how to get label.
URL url = new URL("http://itunes.apple.com/au/rss/topsongs/limit=10/json");
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject itunesJsonObject = new JSONObject(builder.toString());
JSONObject feedJsonOject = itunesJsonObject.getJSONObject("feed");
JSONArray arrayJsonObject = feedJsonOject.getJSONArray("entry");
List<String> list = new ArrayList<>();
for(int i = 0 ; i < arrayJsonObject.length() ; i++){
list.add(arrayJsonObject.getJSONObject(i).getString("title"));
}
for(String e: list){
log.debug("JSON Object : " + e.toString());
}
In log.debug I am geeting following which includes label.
JSON Object : {"label":"Happy (from \"Despicable Me 2\") - Pharrell Williams"}
JSON Object : {"label":"Trumpets - Jason Derulo"}
JSON Object : {"label":"Rude - MAGIC!"}
JSON Object : {"label":"All of Me - John Legend"}
JSON Object : {"label":"Free (feat. Emeli Sandé) - Rudimental"}
JSON Object : {"label":"I See Fire - Ed Sheeran"}
JSON Object : {"label":"Timber (feat. Ke$ha) - Pitbull"}
JSON Object : {"label":"God Only Knows - MKTO"}
JSON Object : {"label":"Like a Drum - Guy Sebastian"}
JSON Object : {"label":"Hey Brother - Avicii"}
My question is on how to get just the title without curly brackets and word label. Also in JSON entry : im:collection has three objects (im:name, link and im:contentType). How to get them invididually.
Thanks for your help in advance.
Upvotes: 1
Views: 1441
Reputation: 31720
The title
is an object with a field called label
, so you'll have to unpack that as well. Something like this might work:
for(int i = 0 ; i < arrayJsonObject.length() ; i++){
list.add(arrayJsonObject.getJSONObject(i).getJSONObject("title").getString("label");
}
Partial raw JSON:
"title": {
"label": "Happy (from \"Despicable Me 2\") - Pharrell Williams"
},
Upvotes: 1