Unable to deserialize when using new Record classes

后端 未结 4 1082
甜味超标
甜味超标 2020-12-10 15:23

I am trying to see if I can replace my existing Pojos with the new Record classes in Java 14. But unable to do so. Getting following error:

com.faste

4条回答
  •  臣服心动
    2020-12-10 16:04

    • Use the parameter names module for jackson, https://github.com/FasterXML/jackson-modules-java8/tree/master/parameter-names (make sure the compiler sets -parameters) or add `@JsonProperty("name") to each field in the record
    • add @JsonCreator to the constructor. I can't tell if the inheritance will work properly, so you might have to explicitly declare the constructor and annotate it.

    If a public accessor method or (non-compact) canonical constructor is declared explicitly, then it only has the annotations which appear on it directly; nothing is propagated from the corresponding record component to these members.

    From https://openjdk.java.net/jeps/384

    So add

    new ObjectMapper().registerModules(new ParameterNamesModule())
    

    and try

    @JsonCreator record Value(String x);
    

    or something like

    record Value(String x) {
    
    @JsonCreator
    public Value(String x) {
    this.x = x;
    }
    }
    

    or all the way to

    record Value(@JsonProperty("x") String x) {
    
    @JsonCreator
    public Value(@JsonProperty("x") String x) {
    this.x = x;
    }
    }
    

    This is how I get immutable pojos with lombok and jackson to work, and I don't see why records wouldn't work under the same format. My setup is Jackson parameter names module, -parameters compiler flag for java 8 (I don't think this is required for like jdk9+), @JsonCreator on the constructor. Example of a real class working with this setup.

    @Value
    @AllArgsConstructor(onConstructor_ = @JsonCreator)
    public final class Address {
    
      private final String line1;
    
      private final String line2;
    
      private final String city;
    
      private final String region;
    
      private final String postalCode;
    
      private final CountryCode country;
    }
    

提交回复
热议问题