在我創建的應用程序中,我從Google Book Api中搜索書籍。例如,考慮這個鏈接https://www.googleapis.com/books/v1/volumes?q=phpJSONException:pageCount沒有值
我可以在屏幕上顯示我想要的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響應,您可以檢查問題開始處的鏈接。
謝謝,
泰奧。
似乎'pageCount'是一個可選屬性(在你鏈接10個結果,只有9個有pageCount)。在試圖解析它之前,你應該檢查它是否存在 – MatPag
@MatPag,我在鏈接的JSON中看到10個'pageCount'項目。可能它根據某些條件而變化。 –
@MatPag,主題你是對的。對於另一個查詢,我得到10箇中有9個具有pageCount。這一個例如https://www.googleapis.com/books/v1/volumes?q=c++ –