我有这个JSON代码并成功为其他键创建了对象,但“authors”键导致了我的问题。我已将数据检索到单个String中,但它包含不需要的字符,因此在我的Adapter类中对其进行了格式化,但我觉得这很草率。
以下是JSON的片段
{
"kind":"books#volumes",
"totalItems":2816,
"items":[
{
"kind":"books#volume",
"id":"6tLAyQLSzG0C",
"etag":"N70szFickpY",
"selfLink":"https://www.googleapis.com/books/v1/volumes/6tLAyQLSzG0C",
"volumeInfo":{
"title":"Android for Work",
"subtitle":"Productivity for Professionals",
"authors":[
"Marziah Karch"
],
"publisher":"Apress",
"publishedDate":"2010-09-01",
这是我从JSON结果中检索数据的方法 -
public static ArrayList<Books> extractBooks(String jsonString) {
ArrayList<Books> books = new ArrayList<>();
String title;
String[] authors;
String published;
String description;
String url;
Bitmap bitmap;
JSONObject imageLinks = null;
try {
JSONObject baseJsonObject = new JSONObject(jsonString);
JSONArray jsonArray = baseJsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i ++) {
JSONObject currentBook = jsonArray.getJSONObject(i);
JSONObject items = currentBook.getJSONObject("volumeInfo");
JSONArray authorArray = items.getJSONArray("authors");
authors = new String[authorArray.length()];
for (int a = 0; a < jsonArray.length(); a++) {
authors[a]= jsonArray.getString("authors");
Log.i(LOG_TAG, "String[] authors: " + authors);
}
//TODO: Fixed? Keep testing.
if (items.has("imageLinks")) {
imageLinks = items.getJSONObject("imageLinks");
String image = imageLinks.getString("smallThumbnail");
bitmap = extractImages(image);
} else {
bitmap = extractImages("http://books.google.com/books/content?id=M_bMehaHiG0C&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api");
}
Boolean hasCover = items.has("imageLinks");
Log.i(LOG_TAG, "has imageLinks - " + hasCover.toString());
if (items.has("title")){
title = items.getString("title");
} else {
title = "No title available";
}
//TODO: Fix authors value to "list" or "array" rather than patching with String.replace in BooksAdapter
// if (author.has("authors")){
// author = items.toString("authors");
// } else {
// author = ("No author available");
// }
if (items.has("publishedDate")) {
published = items.getString("publishedDate");
} else {
published = null;
}
if (items.has("description")){
description = items.getString("description");
} else {
description = "No description available";
}
if (items.has("infoLink")) {
url = items.getString("infoLink");
} else {
url = "none";
}
//TODO:Add key for ebook:True||False so can add icon over cover for Google Play Books
Books book = new Books(title, bitmap, published, description, url, authors);
books.add(book);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing JSON book results", e);
}
return books;
}
正如您所看到的,这是在进行中!我正在尝试创建一个for
循环来遍历“authors”键并将结果保存在String []中。它没有用,我得到一个错误“没有作者的价值”。我可以看到,一旦我去了那把钥匙,我没有价值可以参考,但我不知道该如何继续。
答案 0 :(得分:1)
authors":[ // your json array
"Marziah Karch"
],
所以authors
包含字符串值,因此您应该使用索引a
你需要使用
authors[a] = authorArray.getString(a);
// i recommend to use optString as authorArray.optString(a);