JSON Exception - No value for desired parameter
I am developing an Android application that receives YouTube search results in JSON format and puts the title, channel name and thumbnail thumbnail into the list. I must also add that I am using the android jsoup library. Basically I am connecting to a URL that contains a JSON response and I am trying to use the values ββfrom that response and apply them to a list. Here is the method.
public void initSearch(String searchQuery) {
String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&order=rating&q=" + searchQuery + "&key=MY_GOOGLE_API_KEY";
try {
Document doc = Jsoup.connect(url).ignoreContentType(true).timeout(10 * 1000).get();
String getJson = doc.text();
try{
JSONObject jsonObject = (JSONObject) new JSONTokener(getJson).nextValue();
String videoId = jsonObject.getString("videoId");
String thumbnail = "http://img.youtube.com/vi/" + videoId + "/mqdefault.jpg";
String title = (String)jsonObject.get("title");
String channelTitle = (String)jsonObject.get("channelTitle");
VideoDetails videoDetails = new VideoDetails(thumbnail, title,channelTitle,"6,900" );
searchedList.add(videoDetails);
} catch (JSONException e){
e.printStackTrace();
}
} catch (IOException e){
e.printStackTrace();
}
}
Here is the webpage I'm connecting from.
I've already checked if it is a valid JSON format and yes it is.
Now the problem is that nothing has been added to my list. When this method is called, I get an error that looks like this.
W/System.err: org.json.JSONException: No value for videoId
Does anyone know what's going on? Thanks in advance.
source to share
videoId
is a subelement in JSON, so you need to traverse the JSON to get it.
Bad way (note the hardcoded index):
String videoID = (String) ((JSONObject) ((JSONObject) jsonObject.getJSONArray("items").get(0)).get("id")).get("videoId");
System.out.println(videoID);
Preferred way:
Iterator<?> keys = jsonObject.keys();
/* Iterate over all the elements and sub-elements and assign as
* needed. Based on the type you can concert each item to a JSONObject or
* JSONArray, etc.
*/
while (keys.hasNext()) {
String key = (String) keys.next();
System.out.println(key + "\t" + jsonObject.get(key) + "\t" + jsonObject.get(key).getClass());
}
source to share