ObjectMapper can't deserialize without default constructor after upgrade to Spring Boot 2

前端 未结 7 1584
予麋鹿
予麋鹿 2020-12-24 01:42

I have following DTOs:

@Value
public class PracticeResults {
    @NotNull
    Map wordAnswers;
}

@Value
public class ProfileMetaDto {

         


        
7条回答
  •  囚心锁ツ
    2020-12-24 01:51

    One more way to solve this problem. Use Jackson parameter names module, which is included in spring boot 2 by default. After this Jackson can deserialize objects. But it works only if you have more than 1 property in object. In case of single property I receive following error message:

    com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `SomeClassName` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
    

    Because of the following:

    Marker annotation that can be used to define constructors and factory methods as one to use for instantiating new instances of the associated class.

    NOTE: when annotating creator methods (constructors, factory methods), method must either be:

    • Single-argument constructor/factory method without JsonProperty annotation for the argument: if so, this is so-called "delegate creator", in which case Jackson first binds JSON into type of the argument, and then calls creator. This is often used in conjunction with JsonValue (used for serialization).
    • Constructor/factory method where every argument is annotated with either JsonProperty or JacksonInject, to indicate name of property to bind to

    Also note that all JsonProperty annotations must specify actual name (NOT empty String for "default") unless you use one of extension modules that can detect parameter name; this because default JDK versions before 8 have not been able to store and/or retrieve parameter names from bytecode. But with JDK 8 (or using helper libraries such as Paranamer, or other JVM languages like Scala or Kotlin), specifying name is optional.

    To handle this case with Lombok I've used following workaround:

    @Value
    @AllArgsConstructor(onConstructor = @__(@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)))
    class SomeClassName {...}
    

提交回复
热议问题