Create an array of all keys in Android JSONObject

Hi, I want to create an array of all keys in a JSONObject. my understanding (please correct me if I am wrong) that I need to convert a JSONObject to a map and then create an array from this, does anyone know how to do this?

+4
source share
3 answers

No need to convert a JSONObject to a map and then create an array of keys, just use JSONObject.names () to get all the keys in JsonArray then convert it to Array or ArrayList. Example:

 JSONObject json = new JSONObject("json object string"); JSONArray namearray=json.names(); //<<< get all keys in JSONArray 
+13
source

Use the iterator [ keys() ] [1] to iterate over all properties and call [ get() ] [2] for each.

 Iterator<String> iter = json.keys(); while (iter.hasNext()) { String key = iter.next(); try { Object value = json.get(key); } catch (JSONException e) { // Something went wrong! } } 
+1
source

Try the following:

 ArrayList<String> list = new ArrayList<String>(); JSONArray jsonArray = (JSONArray)jsonObject; if (jsonArray != null) { int len = jsonArray.length(); for (int i=0;i<len;i++){ list.add(jsonArray.get(i).toString()); } } String[] array = list.toArray(new String[list.size()]); 
0
source

All Articles