英文:
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
for (int i = 0; i < authors.length(); i++) {
String author = authors.getString(i);
//将作者添加到您的数组中
authorarray.add(author);
}
英文:
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);
}
答案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<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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论