我有这个 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!",
我必须通过这段代码提取 3 个键“title”、“author”和“description”:
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");
“标题”和“描述”工作正常,但作者部分没有。如我所见,“author”实际上是一个 JSONArray,所以我在屏幕上的输出是
["Nicholas Allan"]
这不是我想要的。所以,我尝试改变我的方法并通过这段代码提取元素
JSONArray author = volumeInfo.getJSONArray("authors");
String authors = author.get(0);
但是Android Studio 说方法get() 的输入必须是一个字符串。 我是 JSON 和 Android 的新手,所以我从未见过没有像这样的值的 JSON key 。谁能告诉我如何从 JSONArray 中提取元素?
最佳答案
自 get()
方法返回一个对象,您需要将其转换为字符串:
String authors = (String) author.get(0);
或者,您可以使用 JSONArray 的 getString(index)
方法,其中 0
是索引。
JSONArray author = volumeInfo.getJSONArray("authors");
String authors = author.getString(0);
关于java - 从 Android 中的 JSONArray 中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45337843/