Search code examples
javaspringspring-bootjacksonjava-record

Jackson can't construct Record without repeating @JsonProperty (Spring Boot)


I have the following immutable DTO:

@Builder
@With
public record MyDTO(
  String field1,
  String field2
) { }

Jackson can't construct this record object

...
InvalidDefinitionException: Cannot construct instance of `com.package.MyDTO`
(no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
...

I am using Java 18, Spring Boot 2.6.7 and Jackson 2.13.3

The way I solved it is to instruct Jackson where to inject which JSON property:

@Builder
@With
public record MyDTO(

  @JsonProperty("field1")
  String field1,

  @JsonProperty("field2")
  String field2
) { }

This approach, however, does not scale and is error prone (repeating field definitions). Is it possible to make it work without @JsonProperty?


Solution

  • Records are supported by the Jackson version 2.12.x. No need for @JsonProperty on every constructor argument.

    The problem was that Spring was using a different, transitive, older Jackson version from another package.