Jackson: deserialize immutable objects with Lombok Value annotation

Elvis Ciotti
1 min readJun 14, 2023

--

The problem

Jackson object mapper with default options is not able to deserialize objects annotated with Lombok Value. If you try to do so, you’ll get an error like Cannot construct instance of yourClass (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator).

Spring 6 Jackson2ObjectMapperBuilder is configured to being able to deserialise those classes, I’ll explain below why.

The reason

The lombok Value annotation makes the class immutable by making class and fields final (in addition to AllArgsContructor, toString, equals, hashCode that the specular non-immutable Data annotation does).

The solution

I’ve solved the problem by enabling the jackson ParameterModule. According to the documentation , this module detects constructor and factory method (“creator”) parameters without having to use @JsonProperty annotation.

// on the ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new ParameterNamesModule());

// or on the builder
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.modules(new ParameterNamesModule(), ... );
ObjectMapper objectMapper = builder.build();

I’ve discovered this by debugging a working deserialization happening using Spring ObjectMapper bean constructed from the Jackson2ObjectMapperBuilder spring bean; this last bean included the module above, whilst my unit test was not using and failed where the application actually worked.

Clap if useful, follow me for more.

--

--

Elvis Ciotti
Elvis Ciotti

Written by Elvis Ciotti

Software Contractor — Java, Spring, k8s, AWS, Javascript @ London - hire me at https://elvisciotti.github.io/

No responses yet