-1

I want to extract authors from this JSON, I successfully get the JSONArray but I don't know how to convert it into String[], I have to pass this String[] to a method. Please try to keep the solution simple as I am just a beginner.

JSON :

{
  "volumeInfo": {
    "title": "Android",
    "authors": [
      "P.K. Dixit"
    ]
  }
}

Code:

JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
// Extract the value for the key called "title"
String title = volumeInfo.optString("title");
// Extract the array for the key called "authors"
JSONArray authors = volumeInfo.optJSONArray("authors");
iknow
  • 8,358
  • 12
  • 41
  • 68
Arya
  • 43
  • 1
  • 9

2 Answers2

1
private ArrayList<String> authorarray = new ArrayList<String>();    

for (int i = 0; i < authors.length(); i++) {
    String author = authors.getString(i);
    //add author to your array
    authorarray.add(author);
    }
aryanknp
  • 1,135
  • 2
  • 8
  • 21
0

Use this function

String[] authors_arr(JSONArray authors){
    String[] authors_res=new String[authors.length()];
    try {
    for(int i=0;i<authors.length();i++)
    {
        authors_res[i]=authors.getString(i);
    }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return authors_res;
}

call it like this String[] authors_string_array = authors_arr(authors); The main point is to loop through your json array and add it into your array

Code Demon
  • 1,256
  • 1
  • 9
  • 15