作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我无法在此 Json 响应中提取书籍缩略图的 URL: https://www.googleapis.com/books/v1/volumes?q=java&maxResults=10
当我将链接硬编码到字符串值中时,它可以工作,因此它一定是我获取缩略图的方法。
这是我的代码:
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(bookwormJSON);
// Extract the JSONArray associated with the key called "items",
// which represents a list of Books.
JSONArray bookwormArray = baseJsonResponse.getJSONArray("items");
// For each bookworm in the bookwormArray, create an {@link Book} object
for (int i = 0; i < bookwormArray.length(); i++) {
JSONObject volumeInfo = bookwormArray.getJSONObject(i).getJSONObject("volumeInfo");
String author = "dork";
// Extract the value for the key called "title"
String title = volumeInfo.getString("title");
// Extract the value for the key called "author - I just get first one in array"
JSONArray authors = volumeInfo.getJSONArray("authors");
author = authors.getString(0);
String imgUrl = volumeInfo.getString("smallThumbnail");
imgUrl = imgUrl.substring(0, 4) + 's' + imgUrl.substring(4);
// title, author and url from the JSON response.
Book bookworm = new Book(title, author,imgUrl );
// When url hardcoded and above related code to url is removed it works.
// Add the new {@link Earthquake} to the list of Books.
bookworms.add(bookworm);
}
}
最佳答案
我发现这些嵌套的 Json 文件/字符串很令人困惑,但我确实通过阅读此处的另一篇文章使上述内容正常工作。如果有人感兴趣的话,这是代码:
在此处输入代码
尝试{ //从 JSON 响应字符串创建 JSONObject JSONObject baseJsonResponse = new JSONObject(bookwormJSON);
// Extract the JSONArray associated with the key called "items",
// which represents a list of Books.
JSONArray bookwormArray = baseJsonResponse.getJSONArray("items");
// For each bookworm in the bookwormArray, create an {@link Book} object
for (int i = 0; i < bookwormArray.length(); i++) {
JSONObject volumeInfo = bookwormArray.getJSONObject(i).getJSONObject("volumeInfo");
//Below is the key line
JSONObject imageLinks = volumeInfo.getJSONObject("imageLinks");
// Extract the value for the key called "title"
String title = volumeInfo.getString("title");
// Extract the value for the key called "author - I just get first one in array"
JSONArray authors = volumeInfo.getJSONArray("authors");
String author = authors.getString(0);
// Extract the value for the key called "smallThumbnail"
String imgUrl= imageLinks.getString("smallThumbnail");
// insert "s" into http
imgUrl = imgUrl.substring(0, 4) + 's' + imgUrl.substring(4);
// title, author and url from the JSON response.
Book bookworm = new Book(title, author,imgUrl );
// Add the new {@link Earthquake} to the list of books.
bookworms.add(bookworm);
}
关于java - 从 Google 图书 api 获取缩略图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60879353/
我是一名优秀的程序员,十分优秀!