Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Exception - No value for wanted parameter

I am developing an app on the android platform that gets youtube video search results as a JSON format and puts the title, channel name, and thumbnail url into a listview. I should also add that I am using the jsoup library for android. Pretty much I am connecting to a URL that contains a JSON response and am trying to use values from that response and apply them to a listview. 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 what the webpage I am connecting to looks like.

I have already checked if it is valid JSON format, and yes it is.

Now the problem is, nothing is actually added to my list view. When this method is called I receive an error that looks like this.

W/System.err: org.json.JSONException: No value for videoId 

Anyone know whats going on? Thanks in advance.

like image 255
Mason Avatar asked Jul 21 '26 09:07

Mason


1 Answers

The videoId is a sub-element in the JSON, so you need to traverse the JSON to get it.

Bad way (note the hard coded 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());
}
like image 111
tima Avatar answered Jul 23 '26 23:07

tima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!