2017-08-04 19 views
0

在我創建的應用程序中,我從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響應,您可以檢查問題開始處的鏈接。

謝謝,

泰奧。

+2

似乎'pageCount'是一個可選屬性(在你鏈接10個結果,只有9個有pageCount)。在試圖解析它之前,你應該檢查它是否存在 – MatPag

+1

@MatPag,我在鏈接的JSON中看到10個'pageCount'項目。可能它根據某些條件而變化。 –

+1

@MatPag,主題你是對的。對於另一個查詢,我得到10箇中有9個具有pageCount。這一個例如https://www.googleapis.com/books/v1/volumes?q=c++ –

回答

3

似乎pageCount是一個可選屬性(在10個結果的鏈接中,只有9個具有pageCount)。

在試圖解析它之前,你應該檢查屬性是否存在。試圖檢索值

//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"); 
} 

書之前就存在,當

1-使用默認值:

你有2個選擇API缺少一些文檔。如果你搜索here屬性volumeInfo.pageCount還沒有關於是可選性的注意事項

+1

Yeap。這就是訣竅。謝謝你的先生。 – Theo