DEV Community

Geoff Bourne
Geoff Bourne

Posted on

3 2

Jackson JSON parsing top-level map into records

Java 14 added the record type and Jackson JSON works great with them.

I hit an edge case where I needed to parse a JSON structure where the top level was an object with arbitrary keys.

I also didn't want to read into a Map but rather a record that mapped each keyed entry into a record each.

Here's a contrived example JSON I wanted to parse:

{
  "Some Child's Name": {
    "age": 5
  },
  "Some Adult's Name": {
    "age": 21
  }
}
Enter fullscreen mode Exit fullscreen mode

The @JsonAnySetter annotation (1) on a Map field got me most of the way, but the final piece of the solution was to pre-instantiate the map at (2).

Here are the final record declarations that can accommodate the JSON above:

record People(
    @JsonAnySetter // (1)
    Map<String, Person> people
) {
    public People {
        people = new HashMap<>(); // (2)
    }
}

record Person(
    int age
) { }
Enter fullscreen mode Exit fullscreen mode

For example, following use of an ObjectMapper ...

final People people = objectMapper.readValue("""
    {
      "Some Child's Name": {
        "age": 5
      },
      "Some Adult's Name": {
        "age": 21
      }
    }""", People.class);
System.out.println(people);
Enter fullscreen mode Exit fullscreen mode

outputs

People[people={Some Adult's Name=Person[age=21], Some Child's Name=Person[age=5]}]
Enter fullscreen mode Exit fullscreen mode

API Trace View

Struggling with slow API calls? 🕒

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay