从Android中的JSONArray中提取值

时间:2017-07-26 21:35:42

标签: java android json

我有这个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()的输入必须是String。 我是JSON和Android的新手,所以我从未见过没有像这样的值的JSON密钥。任何人都可以告诉我如何从JSONArray中提取元素?

1 个答案:

答案 0 :(得分:3)

由于get()方法返回一个Object,您需要将其强制转换为String:

String authors = (String) author.get(0);

或者,您可以使用JSONArray的getString(index)方法,其中0是索引。

JSONArray author = volumeInfo.getJSONArray("authors");
String authors = author.getString(0);