Rahil Arora Rahil Arora - 3 months ago 12
JSON Question

Extracting Keys from a JSONObject using keySet()

I'm trying to extract the keys from a JSON Object. The JSON object, in this case, is obtained by making an API call to a social networking site called SkyRock and looks like this :

"max_page": 2,
"posts": {
"3111623007": {
"id_post": 3111623007,
"media_align": "float_left",
"tags": [],
"nb_comments": 24
"3114564209": {
"id_post": 3114564209,
"media_align": "float_left",
"tags": [],
"nb_comments": 33
"3116902311": {
"id_post": 3116902311,
"media_align": "float_left",
"tags": [],
"nb_comments": 29

I basically want to store all the post_id values in an ArrayList. In order to do this, am trying to extract the keys from the JSON object and am doing this as follows:

JSONObject posts = (JSONObject) jo.get("posts");
ArrayList<String> keys = (ArrayString<String>) posts.keyset();

The problem is that am not able to find a suitable variable type in which I can store the result obtained from the keyset() method.

I tried searching for the answers, but in most of the cases, keys() is being used to extract the keys (which am not able to use for some reason and I think it's maybe because am using org.json.simple, but am not sure).

Can anyone please help me out here to find a solution to the problem or any alternate method to retrieve the Key values?



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 you want:

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