首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSONException: pageCount没有值

JSONException: pageCount没有值
EN

Stack Overflow用户
提问于 2017-08-04 14:40:29
回答 1查看 153关注 0票数 0

在我创建的应用程序中,我从Google Book Api中搜索图书。例如,考虑以下链接https://www.googleapis.com/books/v1/volumes?q=php

我可以在屏幕上以列表视图的形式显示我想要的json对象,并在单击行时使用图书的详细数据启动一个新的活动。即使一切都显示在屏幕上而没有任何崩溃,我也会得到以下异常。

代码语言:javascript
复制
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解析代码。

代码语言:javascript
复制
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响应,您可以检查问题开头的链接。

谢谢,

西奥。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-04 14:55:58

似乎pageCount是一个可选的属性(在你有10个结果的链接中,只有9个有pageCount)。

在尝试解析它之前,您应该检查该属性是否存在。

您有两个选择:

1-尝试检索值时使用默认值

代码语言:javascript
复制
//this will give you 0 as default if pageCount not exists
int pageCount = volumeInfo.optInt("pageCount");

2-在检索之前检查属性是否存在

代码语言:javascript
复制
//this will set pageCount value only if pageCount exists
if (volumeInfo.has("pageCount")){
    int pageCount = volumeInfo.getInt("pageCount");
}

Book API缺少一点文档。如果你搜索herevolumeInfo.pageCount没有注意到的属性是可选性

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45499800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档