Java - JSONArray有10个对象,但只显示前两个

时间:2018-01-22 14:52:21

标签: java android json parsing

我是Android和Java的新手,所以我正在构建一个书籍列表的演示应用程序,以了解解析JSON数据。我使用日志检查数据上有多少本书(10个),但在模拟器上运行时,只显示列表中的2本第一本书...希望有人能告诉我应该在哪里更改? 感谢您的任何意见!

E/QueryUtils: length of array: 10

This is the screenshot of the app which shows only two items

API链接:https://www.googleapis.com/books/v1/volumes?q=search+terms

QueryUtils.java

 private static List<BookItem> extractItemFromJson(String bookJSON) {
        // If the JSON string is empty or null, then return early.
        if (TextUtils.isEmpty(bookJSON)){
            return null;
        }

    // Create an empty ArrayList that we can start adding books to
    List<BookItem> bookItems = new ArrayList<>();

    // Try to parse the JSON response string. If there is a problem with the way the JSON is formatted,
    // a JSONException exception object will be thrown.
    // Catch the exception so the app doesnt crash, and prent the error message to the logs.
    try {
        JSONObject baseJsonresponse = new JSONObject(bookJSON);
        JSONArray bookItemArray = baseJsonresponse.getJSONArray("items");
        Log.e("QueryUtils", "length of array: " + bookItemArray.length());
        for (int i = 0; i < bookItemArray.length(); i++) {
            JSONObject currentBook = bookItemArray.getJSONObject(i);
            JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
            String title = volumeInfo.getString("title");
            String subtitle = volumeInfo.getString("subtitle");
            String previewLink = volumeInfo.getString("previewLink");
            JSONObject imageLinks = volumeInfo.getJSONObject("imageLinks");
            String thumbnail = imageLinks.getString("smallThumbnail");

            BookItem book = new BookItem(/**author, */title, subtitle, thumbnail, previewLink);
            bookItems.add(book);
        }
    } catch (JSONException e) {
        Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
    }

    return bookItems;
}

2 个答案:

答案 0 :(得分:0)

我怀疑它在解析前2后会进入catch块,因为解析时发生了异常,你应该修复异常,你也可以捕获循环中的异常以添加可以解析的项目如果有.active,则不要退出循环。

答案 1 :(得分:0)

列表中的第三本书并没有包含字段imageLinks,这会导致异常 你应该添加一张支票:

String thumbnail = "";
if (volumeInfo.has("imageLinks")) {
    JSONObject imageLinks = volumeInfo.getJSONObject("imageLinks");
    thumbnail = imageLinks.getString("smallThumbnail");
}