【发布时间】:2017-07-27 05:44:54
【问题描述】:
我有这个 JSON 对象
{
"kind": "books#volumes",
"totalItems": 482,
"items": [
{
"kind": "books#volume",
"id": "MoXpe6H2B5gC",
"etag": "6dr4Ka3Iksc",
"selfLink": "https://www.googleapis.com/books/v1/volumes/MoXpe6H2B5gC",
"volumeInfo": {
"title": "Android in The Attic",
"authors": [
"Nicholas Allan"
],
"publisher": "Hachette UK",
"publishedDate": "2013-01-03",
"description": "Aunt Edna has created a no-nonsense nanny android to make sure Billy and Alfie don't have any fun. But then Alfie discovers how to override Auntie Anne-Droid's programming and nothing can stop them eating all the Cheeki Choko Cherry Cakes they like ... until the real aunt Edna is kidnapped!",
我必须通过这段代码 sn-p 提取 3 个键“标题”、“作者”和“描述”:
JSONObject baseJsonResponse = new JSONObject(bookJSON);
// Extract the JSONArray associated with the key called "features",
// which represents a list of features (or books).
JSONArray bookArray = baseJsonResponse.getJSONArray("items");
// For each book in the bookArray, create an {@link book} object
for (int i = 0; i < bookArray.length(); i++) {
// Get a single book at position i within the list of books
JSONObject currentBook = bookArray.getJSONObject(i);
// For a given book, extract the JSONObject associated with the
// key called "volumeInfo", which represents a list of all volumeInfo
// for that book.
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
// Extract the value for the key called "title"
String title = volumeInfo.getString("title");
// Extract the value for the key called "authors"
String authors = volumeInfo.getString("author");
// Extract the value for the key called "description"
String description = volumeInfo.getString("description");
“标题”和“描述”工作正常,但作者部分没有。如我所见,“作者”实际上是一个 JSONArray,所以我在屏幕上的输出是
["Nicholas Allan"]
这不是我想要的。所以,我尝试改变我的方法并通过这段代码提取元素
JSONArray author = volumeInfo.getJSONArray("authors");
String authors = author.get(0);
但是 Android Studio 说方法 get() 的输入必须是一个字符串。 我是 JSON 和 Android 的新手,所以我从未见过没有像这样的值的 JSON 键。谁能告诉我如何从 JSONArray 中提取元素?
【问题讨论】: