我有一個ListView
和3 TextView
,它將顯示圖書標題,作者和來自圖書清單API的發佈日期。在Java中解析JSON時出現問題?
現在,這裏的問題是,我可以顯示書籍的標題和日期,但作者元件爲JSONArray
,對於我在想運行一個內部的循環,將增加作者的字符串變量中,但由於串變量是在內部循環內,當我嘗試將變量傳遞給Book自定義類時,它不可見。
我可以在「volumeInfo
」JSONObject
之內顯示String
,這是「作者」JSONArray
給我的問題。
對不起,沒有解釋清楚,但任何幫助,將不勝感激。
這裏是我的JSON格式
{
"kind":"books#volumes",
"totalItems":1045,
"items":[
{
"kind":"books#volume",
"id":"RVhsAQAAQBAJ",
"etag":"6uHhm1spXck",
"selfLink":"https://www.googleapis.com/books/v1/volumes/RVhsAQAAQBAJ",
"volumeInfo":{
"title":"Android Programming",
"subtitle":"The Big Nerd Ranch Guide",
"authors":[
"Bill Phillips",
"Brian Hardy"
],
"publisher":"Pearson Education",
"publishedDate":"2013",
這裏是我的Java代碼:
List<Book> bookLists = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(bookJSON);
JSONArray bookArray = baseJsonResponse.getJSONArray("items");
for (int i = 0; i <= bookArray.length(); i++) {
JSONObject currentBook = bookArray.getJSONObject(i);
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
String bookTitle = volumeInfo.optString("title").toString();
JSONArray authorArray = currentBook.getJSONArray("authors");
for (int j =0; j <= authorArray.length(); j++) {
String authorBook = authorArray.optString(0).toString(); // error
}
String publishedDate = volumeInfo.optString("publishedDate").toString();
Book book = new Book(bookTitle, authorBook, publishedDate);
bookLists.add(book);
}
} catch (JSONException e){
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
return bookLists;
'String authorBook;/* for循環分配值* /' – vlaz