如何将JSONArray转换为Java字符串数组

huangapple go评论74阅读模式
英文:

How to convert JSONArray to Java String Array

问题

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");
英文:

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");

答案1

得分: 1

private ArrayList authorarray = new ArrayList();

for (int i = 0; i < authors.length(); i++) {
String author = authors.getString(i);
//将作者添加到您的数组中
authorarray.add(author);
}

英文:
private ArrayList&lt;String&gt; authorarray = new ArrayList&lt;String&gt;();    

for (int i = 0; i &lt; authors.length(); i++) {
    String author = authors.getString(i);
    //add author to your array
    authorarray.add(author);
    }

答案2

得分: 0

使用此函数

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;
}

像这样调用它 String[] authors_string_array = authors_arr(authors);
主要目的是遍历您的 JSON 数组并将其添加到您的数组中。

英文:

Use this function

String[] authors_arr(JSONArray authors){
    String[] authors_res=new String[authors.length()];
    try {
    for(int i=0;i&lt;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

huangapple
  • 本文由 发表于 2020年8月8日 20:58:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63315699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定