java - value - jsonelement to jsonobject




Java GSON: Getting the list of all keys under a JSONObject (3)

I have got GSON as a JSON parser in Java, but the keys aren't always the same.
For example. I have the following JSON:

{ "The Object I already know": {
"key1":"value1",
"key2":"value2",
"AnotherObject": { "anotherKey1":"anotherValue1", "anotherKey2":"anotherValue2" }
}

I have already got the JSONObject "The Object I already know". Now I need to get all of the JSONElements for this Object, this would be "Key1", "Key2" and "AnotherObject".
Thanks in advance.
EDIT: The Output should be a String Array with all the keys for the JSONObject


As of Gson 2.8.1 you can use keySet():

String json = "{\"key1\":\"val\", \"key2\":\"val\"}";

JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(json).getAsJsonObject();

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

Since Java 8 you can use Streams as better looking alternative:

String str = "{\"key1\":\"val1\", \"key2\":\"val2\"}";

JsonParser parser = new JsonParser();
JsonObject jObj = (JsonObject) parser.parse(str);

List<String> keys = jObj.entrySet()
    .stream()
    .map(i -> i.getKey())
    .collect(Collectors.toCollection(ArrayList::new));

keys.forEach(System.out::println);

String str = "{\"key1\":\"val1\", \"key2\":\"val2\"}";

        JsonParser parser = new JsonParser();
        JsonObject jObj = (JsonObject)parser.parse(str);

        List<String> keys = new ArrayList<String>();
        for (Entry<String, JsonElement> e : jObj.entrySet()) {
            keys.add(e.getKey());
        }

        // keys contains jsonObject's keys




jsonobject