【发布时间】:2019-08-18 08:01:00
【问题描述】:
我使用Google Books Api 来显示书籍列表,但是当我尝试从imageLinks JSONObject 获取缩略图网址时,JSONException 表示imageLinks 没有任何价值,即使该价值存在于这个对象中。
我尝试了JSONObject.isNull() 或optString() 之类的方法,而不是getString(),但它仍然没有给我任何价值。
这是我试图从中获取数据的 URL:https://www.googleapis.com/books/v1/volumes?q=android
代码如下:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
@Override
public void onResponse(JSONObject response) {
if (response != null) {
try {
JSONArray jsonItemsArray = response.getJSONArray("items");
for (int i = 0; i < jsonItemsArray.length(); i++) {
String thumbnailUrl = "";
String title = "";
JSONObject item = jsonItemsArray.getJSONObject(i);
JSONObject volumeInfo = item.getJSONObject("volumeInfo");
JSONObject thumbnailUrlObject = volumeInfo.getJSONObject("imageLinks");
if (!thumbnailUrlObject.isNull("thumbnail")) {
thumbnailUrl = thumbnailUrlObject.getString("thumbnail");
}
title = volumeInfo.getString("title");
bookList.add(new Book(title, thumbnailUrl));
booksAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
这是一段 JSON 响应:
"kind": "books#volumes",
"totalItems": 500,
"items": [
{
"kind": "books#volume",
"id": "JUVjAgAAQBAJ",
"etag": "kbnCYPNPKq4",
"selfLink": "https://www.googleapis.com/books/v1/volumes/JUVjAgAAQBAJ",
"volumeInfo": {
"title": "Android. Podstawy tworzenia aplikacji",
"authors": [
"Andrzej Stasiewicz"
],
"publisher": "Helion",
"publishedDate": "2013-11-10",
"description": "Na szczęście dostępna jest już książka Android.",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9788324688418"
},
{
"type": "ISBN_10",
"identifier": "8324688412"
}
],
"readingModes": {
"text": true,
"image": true
},
"pageCount": 216,
"printType": "BOOK",
"categories": [
"Computers"
],
"averageRating": 4.0,
"ratingsCount": 1,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": true,
"contentVersion": "1.4.4.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=JUVjAgAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=JUVjAgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
}
我想知道为什么volumeInfo.getJSONObject("imageLinks") 给我JSONException 没有价值,即使imageLinks 有价值。
【问题讨论】:
标签: java android json google-books jsonexception