Unable to deserialize when using new Record classes

后端 未结 4 1077
甜味超标
甜味超标 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:13

    The compiler generates the constructor and other accessor method for a Record.

    In your case,

      public final class Post extends java.lang.Record {  
      public Post(int, int java.lang.String, java.lang.String);
      public java.lang.String toString();
      public final int hashCode();
      public final boolean equals(java.lang.Object);
      public int userId();
      public int id();
      public java.lang.String title();
      public java.lang.String body();
    }
    

    Here you can see that there is not default constructor which is needed got Jackson. The constructor you used is a compact constructor,

    public Post {
     }
    

    You can define a default/no args constructor as,

    public record Post(int userId, int id, String title, String body) {
        public Post() {
            this(0,0, null, null);
        }
    }
    

    But Jackson uses Getter and Setters to set values. So in short, you can not use Record for mapping the response.

提交回复
热议问题