JSONException:pageCount

时间:2017-08-04 06:40:29

标签: android json

在我创建的应用中,我从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响应,您可以检查问题开头的链接。

谢谢,

西奥。

1 个答案:

答案 0 :(得分:4)

似乎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没有关于选项的注释