dev-resources.site
for different kinds of informations.
Jackson JSON parsing top-level map into records
Published at
6/7/2022
Categories
java
json
jackson
records
Author
itzg
Author
4 person written this
itzg
open
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
}
}
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
) { }
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);
outputs
People[people={Some Adult's Name=Person[age=21], Some Child's Name=Person[age=5]}]
records Article's
14 articles in total
c# advanced: Adding Additional Members to a Record in C#
read article
c# advanced: Enhancing Records Adding Flexibility with Additional Members
read article
c# advance : Introduction to Records in C#
read article
Streamlining Healthcare: The Fusion of Medical Records Management with E-Signatures
read article
Multiplos retornos no Flutter/DART com os Records
read article
Creating and Working with Records in C# 📹
read article
Replacing tuples with records
read article
Creating Effective Code using Java Records
read article
Jackson JSON parsing top-level map into records
currently reading
Practical Java 16 - Using Jackson to serialize Records
read article
💾 Java Records 💿 with Jackson 2.12
read article
💾 Java 14 Records 🐞 with JakartaEE JSON-B
read article
Java Records in Spring Boot Rest API
read article
🚀 Java 14 Records 💾 (Preview)
read article
Featured ones: