Marc Löhe
Notebook on code & software design


Serializing and deserializing IDs and other value objects to Java records with Jackson

Posted on

There are many good reasons to model IDs as value objects. Since Java 16 Records it is very easy to use value objects, but how do you (de-)serialize JSON to these records with Jackson?

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

record MyId(String value) {

    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public MyId {}

    @JsonValue
    public String value() {
        return value;
    }

}