2017-07-26 51 views
0

提取值我有此JSON对象从JSONArray Android中

{ 
"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个键“标题”,“作者”,通过该代码片段“描述”:

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中提取元素?

回答

2

由于get()方法返回一个对象,你需要将它转换为一个字符串:

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

或者,你可以使用JSONArray的getString(index)方法,其中0是该指数。

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