Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:
Getting the List of All Keys Under a JSONObject Using GSON
Last updated: October 6, 2025
1. Overview
When we work with JSON data in Java, one of the everyday tasks we face is extracting all the keys. At first, it looks easy; after all, GSON makes parsing JSON super straightforward. However, as soon as our JSON starts to get nested, things become a bit more challenging.
In this tutorial, we’ll walk through how we can use GSON to get all keys from a JsonObject, including nested ones. We’ll also write some unit tests to ensure our solution works correctly.
2. Why Do We Need This?
Let’s say we have some JSON response from an API, and we want to:
- Validate whether specific keys exist.
- Log all the keys for debugging purposes.
- Flatten the structure for easier comparison or processing.
If our JSON looks simple, like this:
{
"name": "Henry",
"email": "[email protected]",
"age": 25
}
Then calling jsonObject.keySet() gives us all the keys:
[name, email, age]
But as soon as we deal with nested JSON:
{
"name": "Henry",
"email": "[email protected]",
"address": {
"city": "New York",
"zip": "10001"
}
}
jsonObject.keySet() will only return:
[name, email, address]
We lose the nested keys, such as address.city and address.zip. That’s not good if we want a complete list of keys.
3. How To Solve?
We can solve this by writing a recursive method. To begin with, we can use the GSON library. It is a very lightweight and widely used JSON library.
We can have GSON, add it to our pom.xml using Maven dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
Let’s have a look at the implementation:
public static List<String> getAllKeys(JsonObject jsonObject) {
List<String> keys = new ArrayList<>();
extractKeys("", jsonObject, keys);
return keys;
}
private static void extractKeys(String prefix, JsonObject jsonObject, List<String> keys) {
Set<String> jsonKeys = jsonObject.keySet();
for (String key : jsonKeys) {
String fullKey = prefix.isEmpty() ? key : prefix + "." + key;
keys.add(fullKey);
JsonElement element = jsonObject.get(key);
if (element.isJsonObject()) {
extractKeys(fullKey, element.getAsJsonObject(), keys);
}
}
}
Let’s understand the implementation:
- We start with the method getAllKeys(). It prepares a list and calls extractKeys().
- The extractKeys() method goes through all keys of the current object.
- If the value is another JsonObject, we recursively call the same method.
- To make keys meaningful, we add prefixes. Instead of just storing the city, we store the address.city.
Let’s have a look at the supporting test case:
@Test
void givenJson_whenTopLevelKeys_thenGetAllKeys() {
String json = "{ \"name\":\"Henry\", \"email\":\"[email protected]\", \"age\":25 }";
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
List<String> keys = JsonKeyExtractor.getAllKeys(jsonObject);
assertEquals(3, keys.size());
assertTrue(keys.contains("name"));
assertTrue(keys.contains("email"));
assertTrue(keys.contains("age"));
}
@Test
void givenJson_whenNestedKeys_thenGetAllKeys() {
String json = "{ \"address\": { \"city\":\"New York\", \"zip\":\"10001\" } }";
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
List<String> keys = JsonKeyExtractor.getAllKeys(jsonObject);
assertEquals(3, keys.size());
assertTrue(keys.contains("address"));
assertTrue(keys.contains("address.city"));
assertTrue(keys.contains("address.zip"));
}
This way, we don’t miss anything, regardless of how deeply the JSON is nested.
4. Where Can We Use This?
Now that we’ve solved the problem, let’s think about where this is useful in real-world projects:
- Validation: Ensuring required keys are present in an incoming JSON.
- Auditing: Logging the structure of a JSON payload for debugging or compliance.
- Flattening Data: Preparing data for tools that don’t handle nested JSON well.
- Schema Discovery: Exploring unfamiliar APIs without manually inspecting the payload.
5. Conclusion
In this article, we built a simple recursive utility to extract all keys from a JsonObject using GSON. By handling nested objects, we can ensure no keys are missed. The beauty of this approach is that it’s flexible, and we can extend it further if needed to handle arrays or apply filters such as only collecting leaf keys.
Now, the next time we need to work with JSON in Java, we’ll have a reliable way to get every single key.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.















