在我创建的应用程序中,我从Google Book Api中搜索图书。例如,考虑以下链接https://www.googleapis.com/books/v1/volumes?q=php
我可以在屏幕上以列表视图的形式显示我想要的json对象,并在单击行时使用图书的详细数据启动一个新的活动。即使一切都显示在屏幕上而没有任何崩溃,我也会得到以下异常。
08-04 09:30:07.897 29829-30069/com.example.android.booklist
W/System.err: org.json.JSONException: No value for pageCount老实说,我不知道为什么会发生这种事。当我调试获得pageCount int的代码行时,读取的页数没有任何问题。这是我的json解析代码。
private static List<Book> extractFeatureFromJson(String bookJson){
if(TextUtils.isEmpty(bookJson)){
return null;
}
// Create an empty ArrayList that we can start adding earthquakes to
List<Book> books = new ArrayList<>();
String thumbnail=null;
try {
JSONObject baseJSON = new JSONObject(bookJson);
JSONArray itemsJsonArray = baseJSON.getJSONArray("items");
for(int i = 0;i<itemsJsonArray.length(); i++){
JSONObject item = itemsJsonArray.getJSONObject(i);
JSONObject volumeInfo = item.getJSONObject("volumeInfo");
String title = volumeInfo.getString("title");
JSONArray authorsArray = volumeInfo.getJSONArray("authors");
String authors = formatListOfAuthors(authorsArray);
String language = volumeInfo.getString("language");
String date = volumeInfo.getString("publishedDate");
// This line gives me the described exception.
int pageCount = volumeInfo.getInt("pageCount");
if(volumeInfo.has("imageLinks")){
JSONObject imageLinks = volumeInfo.getJSONObject("imageLinks");
thumbnail = imageLinks.getString("smallThumbnail");
}
Book b = new Book(title,authors,thumbnail,date,language,pageCount);
books.add(b);
}
} catch (JSONException e) {
e.printStackTrace();
}
return books;
}有什么想法吗?
对于实际的json响应,您可以检查问题开头的链接。
谢谢,
西奥。
发布于 2017-08-04 14:55:58
似乎pageCount是一个可选的属性(在你有10个结果的链接中,只有9个有pageCount)。
在尝试解析它之前,您应该检查该属性是否存在。
您有两个选择:
1-尝试检索值时使用默认值
//this will give you 0 as default if pageCount not exists
int pageCount = volumeInfo.optInt("pageCount");2-在检索之前检查属性是否存在
//this will set pageCount value only if pageCount exists
if (volumeInfo.has("pageCount")){
int pageCount = volumeInfo.getInt("pageCount");
}Book API缺少一点文档。如果你搜索here,volumeInfo.pageCount没有注意到的属性是可选性
https://stackoverflow.com/questions/45499800
复制相似问题