【问题标题】:JSON Exception - No value for wanted parameterJSON 异常 - 所需参数没有值
【发布时间】:2017-08-06 03:21:27
【问题描述】:

我正在 android 平台上开发一个应用程序,它以 JSON 格式获取 youtube 视频搜索结果,并将标题、频道名称和缩略图 url 放入列表视图中。我还应该补充一点,我正在使用适用于 android 的 jsoup 库。几乎我正在连接到一个包含 JSON 响应的 URL,并尝试使用该响应中的值并将它们应用于列表视图。 方法如下。

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 是我要连接的网页的样子。

我已经检查过它是否是有效的 JSON 格式,是的。

现在的问题是,我的列表视图中实际上没有添加任何内容。调用此方法时,我收到如下所示的错误。

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

有人知道怎么回事吗?提前致谢。

【问题讨论】:

  • 什么是 searchQuery 值?我想测试一下。
  • searchQuery 值来自我在 MainActivity 中实现的 SearchView。我只是使用“狗”作为 searchQuery 术语。
  • 请记住,您必须更改 url 末尾的 api 密钥才能获得授权请求

标签: java android json listview jsoup


【解决方案1】:

videoId是JSON中的子元素,需要遍历JSON才能得到。

不好的方式(注意硬编码索引):

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 很陌生,所以我真的不知道如何在其中导航。当我在调试器中运行您喜欢的方式时,我注意到返回的某些类与其他类不同。更具体地说,“items”键被标记为 JSONArray。我该如何浏览呢?嵌套while循环?如果可能的话,你能给我一些源代码吗?再次感谢你,我离我想要的价值观越来越近了。
  • @Mason JSONArray 的行为就像一个列表,所以当你找到一个时,你可以将它分配给一个 JSONArray 变量,它会有像 sizeget 这样的方法,你可以在循环中使用获取所有值。 JSONArray a = (JSONArray) jsonObject.get(key);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多