【问题标题】:Google Books Api - No value for imageLinks - Android JSONExceptionGoogle Books Api - imageLinks 没有价值 - Android JSONException
【发布时间】:2019-08-18 08:01:00
【问题描述】:

我使用Google Books Api 来显示书籍列表,但是当我尝试从imageLinks JSONObject 获取缩略图网址时,JSONException 表示imageLinks 没有任何价值,即使该价值存在于这个对象中。

我尝试了JSONObject.isNull()optString() 之类的方法,而不是getString(),但它仍然没有给我任何价值。

这是我试图从中获取数据的 URL:https://www.googleapis.com/books/v1/volumes?q=android

代码如下:

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
 @Override
 public void onResponse(JSONObject response) {
  if (response != null) {
   try {
    JSONArray jsonItemsArray = response.getJSONArray("items");
    for (int i = 0; i < jsonItemsArray.length(); i++) {
     String thumbnailUrl = "";
     String title = "";
     JSONObject item = jsonItemsArray.getJSONObject(i);
     JSONObject volumeInfo = item.getJSONObject("volumeInfo");
     JSONObject thumbnailUrlObject = volumeInfo.getJSONObject("imageLinks");
     if (!thumbnailUrlObject.isNull("thumbnail")) {
      thumbnailUrl = thumbnailUrlObject.getString("thumbnail");
     }
     title = volumeInfo.getString("title");
     bookList.add(new Book(title, thumbnailUrl));
     booksAdapter.notifyDataSetChanged();
    }

   } catch (JSONException e) {
    e.printStackTrace();
   }
  }
 }
}, new Response.ErrorListener() {
 @Override
 public void onErrorResponse(VolleyError error) {
  error.printStackTrace();
 }
});

这是一段 JSON 响应:

"kind": "books#volumes",
 "totalItems": 500,
 "items": [
  {
   "kind": "books#volume",
   "id": "JUVjAgAAQBAJ",
   "etag": "kbnCYPNPKq4",
   "selfLink": "https://www.googleapis.com/books/v1/volumes/JUVjAgAAQBAJ",
   "volumeInfo": {
    "title": "Android. Podstawy tworzenia aplikacji",
    "authors": [
     "Andrzej Stasiewicz"
    ],
    "publisher": "Helion",
    "publishedDate": "2013-11-10",
    "description": "Na szczęście dostępna jest już książka Android.",
    "industryIdentifiers": [
     {
      "type": "ISBN_13",
      "identifier": "9788324688418"
     },
     {
      "type": "ISBN_10",
      "identifier": "8324688412"
     }
    ],
    "readingModes": {
     "text": true,
     "image": true
    },
    "pageCount": 216,
    "printType": "BOOK",
    "categories": [
     "Computers"
    ],
    "averageRating": 4.0,
    "ratingsCount": 1,
    "maturityRating": "NOT_MATURE",
    "allowAnonLogging": true,
    "contentVersion": "1.4.4.0.preview.3",
    "imageLinks": {
     "smallThumbnail": "http://books.google.com/books/content?id=JUVjAgAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
     "thumbnail": "http://books.google.com/books/content?id=JUVjAgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
    }

我想知道为什么volumeInfo.getJSONObject("imageLinks") 给我JSONException 没有价值,即使imageLinks 有价值。

【问题讨论】:

    标签: java android json google-books jsonexception


    【解决方案1】:

    不是每个volumeInfo 节点都有imageLinks 节点,所以你需要使用node.has 方法或node.opt* 方法检查给定节点是否存在,并检查结果是否不是null。您可以在下面找到获取thumbnail节点的安全方法:

    JSONObject thumbnailUrlObject = volumeInfo.optJSONObject("imageLinks");
    if (thumbnailUrlObject != null && thumbnailUrlObject.has("thumbnail")) {
        thumbnailUrl = thumbnailUrlObject.getString("thumbnail");
    }
    

    显示其工作原理的简单控制台应用程序:

    import org.json.JSONArray;
    import org.json.JSONObject;
    
    import java.io.File;
    import java.nio.file.Files;
    
    public class OrgJsonApp {
    
        public static void main(String[] args) throws Exception {
            File jsonFile = new File("./resource/test.json").getAbsoluteFile();
            String json = String.join("", Files.readAllLines(jsonFile.toPath()));
    
            JSONObject response = new JSONObject(json);
    
            // get items
            JSONArray jsonItemsArray = response.getJSONArray("items");
            for (int i = 0; i < jsonItemsArray.length(); i++) {
                String thumbnailUrl = "";
                JSONObject item = jsonItemsArray.getJSONObject(i);
                JSONObject volumeInfo = item.getJSONObject("volumeInfo");
                JSONObject thumbnailUrlObject = volumeInfo.optJSONObject("imageLinks");
                if (thumbnailUrlObject != null && thumbnailUrlObject.has("thumbnail")) {
                    thumbnailUrl = thumbnailUrlObject.getString("thumbnail");
                }
                String title = volumeInfo.getString("title");
                System.out.println("title => " + title);
                System.out.println("thumbnail => " + thumbnailUrl);
            }
        }
    }
    

    JSON 有效载荷打印的上述代码:

    title => Android Aplikacje wielowątkowe techniki przetwarzania
    thumbnail => 
    title => Android. Receptury
    thumbnail => http://books.google.com/books/content?id=pZ5iAgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
    title => Android. Podstawy tworzenia aplikacji
    thumbnail => http://books.google.com/books/content?id=JUVjAgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
    title => Optymalizacja wydajności aplikacji na Android
    thumbnail => http://books.google.com/books/content?id=WJ1iAgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
    title => Inteligentny dom. Automatyzacja mieszkania za pomocą platformy Arduino, systemu Android i zwykłego komputera
    thumbnail => http://books.google.com/books/content?id=koiKAgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
    title => Android UI. Podręcznik dla projektantów. Smashing Magazine
    thumbnail => http://books.google.com/books/content?id=HEJjAgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
    title => Android. Programowanie gier na tablety
    thumbnail => http://books.google.com/books/content?id=7J1iAgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
    title => Profesjonalne tworzenie gier internetowych dla systemu Android w językach HTML5, CSS3 i JavaScript
    thumbnail => http://books.google.com/books/content?id=vlNjAgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
    title => Beginning Android 2
    thumbnail => http://books.google.com/books/content?id=2XeNswkT_2YC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
    title => Pro Android 2
    thumbnail => http://books.google.com/books/content?id=Bam8K5SIiTkC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
    

    【讨论】:

    • 仍然无法正常工作。正如您在我包含在此问题中的 json 响应中看到的那样,volumeInfo 节点具有 imageLinks 节点,并且它包含带有 url 的缩略图。当我调试这个时,json响应包含带有缩略图节点中的url的imageLinks,但是当应用程序运行时,它仍然没有显示imageLinks的值
    • @rradzzio,如果您计算"volumeInfo" 节点,您将看到11 节点。如果计算"thumbnail" 节点,您将只看到9。所以,有些volumeInfo 没有thumbnail
    • 好的,但它告诉我每个`"volumeInfo"`都没有`"thumbnail"`,即使有些volumeInfos有它
    • @rradzzio,看看我添加到答案中的简单应用程序。它正确显示(无例外)titlethumbnail 属性。
    • 我很高兴听到这个消息。请看How does accepting an answer work?
    猜你喜欢
    • 2013-03-06
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2017-01-03
    • 2013-01-12
    相关资源
    最近更新 更多