'How can I create immutable DTOs using Jackson but without annotions?

Jackson can deserialize JSON data into immutable objects. But by default the constructor or static factory method parameters have to be specified either using @JsonProperty or using @ConstructorProperties. How can I configure Jackson and the compiler so that these annotations are not needed? And how do I best configure these when using Spring Boot?



Solution 1:[1]

When serializing Java 17's records no further steps are needed because records store the names of their components. But when serializing normal classes three configurations are needed:

  • The immutable DTO needs to be compiled with javac's -parameters flag.
  • The ParameterNamesModule needs to be needs to be registered with Jackson's ObjectMapper
  • A special case is when the DTO construct takes a single structured type (e.g. a List or Map). In this case Jackson uses a so called "delegating" mode which is not wanted in this case. This can be changed by configuring the ObjectMapper: mapper.setConstructorDetector(USE_PROPERTIES_BASED). This is supported since Jackson 2.12.

In Spring Boot the first two settings are the default thus no changes are needed. The third configuration can be done by providing a Jackson2ObjectMapperBuilderCustomizer bean:

@Bean public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
  return builder -> builder.postConfigurer(mapper -> mapper.setConstructorDetector(USE_PROPERTIES_BASED));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1