检查jsonArray是否为null

时间:2017-06-03 00:20:16

标签: java android json

我正在尝试检查json数组以获取作者的名称,如果为null我需要给我未知的作者 这个json数组



{  
   "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 个答案:

答案 0 :(得分: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";
}