0

How to get all the names from JSON object as a string array

 {
    "status_code": 200,
    "status": "success",
    "data": [
      {
    "id": 1,
    "name": "Ajay"
    },
      {
    "id": 2,
    "name": "Balaji"
    },
      {
    "id": 3,
    "name": "Vinoth"
    }
    ]
    }

Expected Output :

["Ajay","Balaji","Vinoth"]
keser
  • 2,472
  • 1
  • 12
  • 38
  • Hi priya, welcome to StackOverflow. Have you looked at https://stackoverflow.com/help/how-to-ask – ColonD Aug 30 '18 at 07:35

3 Answers3

0

You can use JSONObject and JSONArray as displayed in the following example:

{'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);
ProgFroz
  • 197
  • 4
  • 17
  • String[] blah = arrays.toArray(jsons);???? how you can convert this...it's a type mismatch...it's never going to compile – Ashwini Saini Aug 30 '18 at 07:57
  • My bad, it would not return a String[]. Your result is a JSONObject[] where you can get the String values. – ProgFroz Aug 30 '18 at 08:07
0

You could simply use Array.map() function.

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.

For info on Array.map() click here.

Hope this helps.

0

it's easy and You can retrieve your desired output like this

the symbol {,} mean json object and [,] indicate an json array

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


        }
Ashwini Saini
  • 1,324
  • 11
  • 20