2017-06-03 71 views
0

我試圖檢查JSON數組得到作者的姓名,如果空我需要給我不知名的作者 這個JSON數組檢查jsonArray如果空或不是

{ 
 
    "kind":"books#volumes", 
 
    "totalItems":604, 
 
    "items":[ 
 
     { 
 
     "kind":"books#volume", 
 
     "id":"6tLAyQLSzG0C", 
 
     "etag":"wtUTTM0nDQA", 
 
     "selfLink":"https://www.googleapis.com/books/v1/volumes/6tLAyQLSzG0C", 
 
     "volumeInfo":{ 
 
      "title":"Android for Work", 
 
      "subtitle":"Productivity for Professionals", 
 
      "authors":[ 
 
       "Marziah Karch" 
 
      ],

和這我的java代碼

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

     // Extract the JSONArray 
     // which represents list of title of book ant author name. 
     JSONArray bookArray = root.getJSONArray("items"); 

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

      // Get a single booka t position i within the list of books 
      JSONObject currentBook = bookArray.getJSONObject(i); 
      JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo"); 
      // Extract the value for the key called " title" 
      String title=""; 
      if(volumeInfo.has("title")) 
      { title = volumeInfo.getString("title");} 
      JSONArray authors= volumeInfo.getJSONArray("authors"); 
      String author = ""; 


       for (int j = 0; j < authors.length(); j++) { 
        if(authors.length()==0){ 
       // Convert the authors to a string 
       author = authors.getString(j);}else{author="unknown";}} 

我可以得到書的標題,但作者的名字總是未知我不知道爲什麼?

回答

1

你的問題是,在這種情況下if(authors.length()==0)

這應該是:

JSONArray authors= volumeInfo.getJSONArray("authors"); 
String author = null; 
if(authors.length() > 0) { 
    author = authors.getString(authors.length() - 1); 
} else { 
    author="unknown"; 
} 
+0

@A Edwar感謝它做 – mohammedragabmohammedborik

+0

@A Edwar我已經接受你的意思?或告訴我我如何接受 – mohammedragabmohammedborik

+0

你的意思是投票回答? – mohammedragabmohammedborik