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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI Live!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️