Jackson is a popular library to serialize Java objects to JSON, and since version 2.12 it also supports records!
Let's see how we can use it.
Reading or writing a record
Records are supported out of the box since Jackson 2.12, and work just as their equivalent POJO
record Customer(UUID id, String firstName) {}
can be read from or written as
{
"id": "7fe05925-18d8-4284-a15c-8af6f33f1d6e",
"firstName": "John"
}
All normal Jackson options and configuration will be respected.
Annotations like JsonAlias, JsonValue or
Known bugs
Unfortunately, the latest Jackson version at the time of writing - 2.13.4 - has done known bugs or unsupported situations with records. Here I list them and provide work-arounds
Scalar values with @JsonValue
Records provide a natural way to wrap a scalar value, introducing a custom type that serializes to the underlying JSON type.
For example, we might want to restrict valid JSON inputs to positive numbers:
record PositiveInt(@JsonValue int value) {
@JsonCreator
PositiveInt {
if(value <= 0) {
throw new IllegalArgumentException("value " + value + " must be positive");
}
}
}
Unfortunately, due to
TODO: describe BUG
Top comments (0)