Extracting Keys from a JSONObject using keySet()

The javadoc says:

public interface JsonObject
extends JsonStructure, Map<String,JsonValue>

So, a JSONObject is a Map whose keys are of type String, and whose values are of type JSONValue.

And the javadoc of Map<K, V>.keySet() says:

Set<K> keySet()

Returns a Set view of the keys contained in this map

So, what JSONObject.keySet() returns is a Set<String> (which is quite logical, since keys of JSON objects are strings).

So all that you want is:

Set<String> keys = posts.keySet();

The posts represents Map of JSONObject where key is String

JSONObject mainObject = new JSONObject(jsonString);

JSONObject posts = mainObject.getJSONObject("posts");

Map<String, JSONObject> map = (Map<String,JSONObject>)posts.getMap();

ArrayList<String> list = new ArrayList<String>(map.keySet());

System.out.println(list);

Output:

[3116902311, 3114564209, 3111623007]

Tags:

Java

Json