JSON异常-所需参数无值 [英] JSON Exception - No value for wanted parameter

查看:84
本文介绍了JSON异常-所需参数无值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Android平台上开发一个应用,该应用以JSON格式获取youtube视频搜索结果,并将标题,频道名称和缩略图网址放入列表视图中.我还应该补充一点,我正在使用Android的jsoup库.我几乎连接到包含JSON响应的URL,并尝试使用该响应中的值并将其应用于列表视图. 这是方法.

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

此处是我要连接的网页.

我已经检查了它是否为有效的JSON格式,是的.

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.

推荐答案

videoId是JSON中的一个子元素,因此您需要遍历JSON才能获取它.

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

首选方式:

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

这篇关于JSON异常-所需参数无值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆