gpt4 book ai didi

java - 从 Google 图书 api 获取缩略图

转载 作者:行者123 更新时间:2023-12-01 17:44:55 26 4
gpt4 key购买 nike

我无法在此 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com