Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW