【问题标题】:Java - JSONArray has 10 objects but only display first twoJava - JSONArray 有 10 个对象,但只显示前两个
【发布时间】:2018-01-22 14:52:20
【问题描述】:

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

E/QueryUtils: length of array: 10

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;
}

【问题讨论】:

  • 如果您的问题很清楚,我们可以判断。 只显示前两个在哪里?
  • @Ravi 仅在应用程序运行时在模拟器设备上的主要活动上显示前两个。嗯,我是否足够清楚?
  • 是的。您需要告诉代码的一部分,即打印两个。

标签: java android json parsing


【解决方案1】:

列表中的第三本书没有包含字段 imageLinks,这会导致异常。
你应该添加一个检查:

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

【讨论】:

  • 是的!非常感谢..我忘了第三本书的位置是(2)而不是(3)..
【解决方案2】:

我怀疑它在解析前 2 个之后会进入 catch 块,因为解析时发生了异常,您应该修复异常,并且您可以在循环内捕获异常以添加可以解析的项目而不是如果有JSONException,则退出循环。

【讨论】:

  • 因为解析时发生异常有什么具体原因吗?
  • @Ravi 不,只是因为我想不出其他原因,而且我知道问题应该更清楚。
  • @AhmedHegazy 哦,谢谢。日志说有no value for imageLinks。了解最初的问题并尝试现在弄清楚为什么 imageLinks 现在没有价值......(虽然我仍然没有发现它为什么这么说)
猜你喜欢
  • 2016-06-21
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多