如何从JSON对象获取所有名称作为字符串数组
{
"status_code": 200,
"status": "success",
"data": [
{
"id": 1,
"name": "Ajay"
},
{
"id": 2,
"name": "Balaji"
},
{
"id": 3,
"name": "Vinoth"
}
]
}
预期输出:
["Ajay","Balaji","Vinoth"]
答案 0 :(得分:0)
您可以使用JSONObject和JSONArray,如以下示例所示:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
答案 1 :(得分:0)
您可以简单地使用Array.map()
函数。
var jsonObj = {
"status_code": 200,
"status": "success",
"data": [
{
"id": 1,
"name": "Ajay"
},
{
"id": 2,
"name": "Balaji"
},
{
"id": 3,
"name": "Vinoth"
}
]
};
var stringArr = jsonObj.data.map(function(el) {
return el.name;
}) // stringArr is now an array that would contain the names.
有关Array.map()
的信息,请单击here。
希望这会有所帮助。
答案 2 :(得分:0)
这很容易,您可以像这样检索所需的输出
符号{,}
表示json对象,[,]
表示json数组
//Here i first take json object from your string
JSONObject jsonObject = new JSONObject(your_json_respons_string);
// now the json object have json array so we will take array
JSONArray jsonArray = jsonObject.getJSONArray("data");
//each json array have one name so definitely our array size going to be jsonArray.length()
String[] strings = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
//taking json object and the name values and then putting in array
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
strings[i] = jsonObject1.getString("name");
}