DEV Community

Geoff Bourne
Geoff Bourne

Posted on

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

Top comments (0)