2017-06-13 2 views
0

Ich bin neu bei der Verwendung von APIs in Android, also mache ich eine einfache App mit Google Books API, also möchte ich den Titel, den Autor und Beschreibung. Dies ist die Methode, die die Informationen extrahiert, aber die Ausnahme auslöst und den catch-Block ausführt. Dies ist die Abfrage „https://www.googleapis.com/books/v1/volumes?q=android&maxResults=1“, wo die bookJSON Variable die Abfrage Antwort ist:Ich erhalte einen Fehler beim Abrufen von Daten aus Google Bücher api

private static List<Book> extractFeatureFromJson(String bookJSON) { 

     if (TextUtils.isEmpty(bookJSON)) { 
      return null; 
     } 

        List<Book> books = new ArrayList<>(); 


     try { 

      // Create a JSONObject from the JSON response string 
      JSONObject baseJsonResponse = new JSONObject(bookJSON); 


      JSONArray itemsArray = baseJsonResponse.getJSONArray("items"); 


      for (int i = 0; i < itemsArray.length(); i++) { 

          JSONObject currentBook = itemsArray.getJSONObject(i); 

       JSONArray authorArray = currentBook.getJSONArray("authors"); 

       StringBuilder authorsStringBuild = new StringBuilder(); 

       for(int j=0; j<authorArray.length(); j++){ 
        authorsStringBuild.append(authorArray.getString(j)); 
        authorsStringBuild.append(", "); 
       } 

       String authors = authorsStringBuild.toString(); 

       String title = currentBook.getString("title"); 

       String description = currentBook.getString("description"); 

       double rating = currentBook.getDouble("averageRating"); 

       Book book = new Book(title, authors ,description , rating); 

       books.add(book); 
      } 

     } catch (JSONException e) { 

      Log.e(LOG_TAG, "Problem parsing the book JSON results", e); 
     } 

     return books; 
    } 

Antwort

0

Bitte die Ausgabe und Fehlerprotokolle in Zukunft stellen. Ich hatte nicht genug Ansehen, um das zu kommentieren. Ich habe Ihren Code ausgeführt und es ist ein JSON-Parsing-Fehler. in Ihrem Code Ersetzen Sie diese Zeile

JSONArray authorArray = currentBook.getJSONArray("authors"); 

mit diesem

itemsArray.getJSONObject(i).getJSONObject("volumeInfo").getJSONArray("authors"); 

Sie die JSONObject fehlten vor "Autoren".

Sie können Online-JSON-Formatierungswerkzeuge verwenden, um die Hierarchie besser zu visualisieren und Ihnen das Leben zu erleichtern. Dies ist die, die ich mag https://jsonformatter.curiousconcept.com/

+0

Vielen Dank, es hat perfekt funktioniert –

+0

Sie sind herzlich willkommen! :) –

Verwandte Themen