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
Iterator <String> listKEY = jsonOject.keys();
do {
String newKEY = listKEY.next().toString();
}while (listKEY.hasNext());
This works for me
o is a JSONObject -> import org.json.simple.JSONObject;
Set<?> s = o.keySet();
Iterator<?> i = s.iterator();
do{
String k = i.next().toString();
System.out.println(k);
}while(i.hasNext());
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]
Recursive methods for extracting keys from json objects and arrays (in case of duplicates will merge them since methods return Set, but not Array)
public static Set<String> getAllKeys(JSONObject json) {
return getAllKeys(json, new HashSet<>());
}
public static Set<String> getAllKeys(JSONArray arr) {
return getAllKeys(arr, new HashSet<>());
}
private static Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
for (int i = 0; i < arr.length(); i++) {
Object obj = arr.get(i);
if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
}
return keys;
}
private static Set<String> getAllKeys(JSONObject json, Set<String> keys) {
for (String key : json.keySet()) {
Object obj = json.get(key);
if (obj instanceof JSONObject) keys.addAll(getAllKeys(json.getJSONObject(key)));
if (obj instanceof JSONArray) keys.addAll(getAllKeys(json.getJSONArray(key)));
}
keys.addAll(json.keySet());
return keys;
}
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();