JSON Exception - No value for wanted parameter

 ̄綄美尐妖づ 提交于 2021-01-27 11:50:21

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/45528247/json-exception-no-value-for-wanted-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!