我正在 android 平台上开发一个应用程序,它以 JSON 格式获取 youtube 视频搜索结果,并将标题、 channel 名称和缩略图 url 放入 ListView 中。我还应该补充一点,我正在使用 android 的 jsoup 库。我几乎连接到一个包含 JSON 响应的 URL,并尝试使用该响应中的值并将它们应用于 ListView 。 这是方法。
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 格式,是的。
现在的问题是,实际上没有任何内容添加到我的 ListView 中。调用此方法时,我会收到如下所示的错误。
W/System.err: org.json.JSONException: No value for videoId
有人知道怎么回事吗?提前致谢。
最佳答案
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());
}
关于java - JSON 异常 - 所需参数没有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45528247/