jackson 当对象具有多个构造函数时,无法使用ObjectMapper进行示例化

enxuqcxy  于 7个月前  发布在  其他
关注(0)|答案(2)|浏览(71)

我得到了以下错误,而具体化的对象。

(no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

我的对象定义是

@Getter
    @Setter
    @ToString
    @Document(collection = "abc")
    @NoArgsConstructor
    @AllArgsConstructor
    public class ABC implements Serializable {
    
      @Id
      private String id;
      @Indexed
      private String number;
      private String a;
      private Long b;
      //added later 
      private String c;
      public ABC(Long b) {
        this.b=b;
      }
      public ABC(String a,Long b) {
        this.b=b;
        this.a=a;
      }
      //added later
      public ABC(String a,Long b,String c) {
        this.b=b;
        this.a=a;
        this.c=c;
     }
  }

我使用objectMapper.readValue(json, new TypeReference<ABC>() {})将json转换为ABC对象。在添加变量c和新的构造函数之前,它工作得很好。我必须添加一个新的构造器来保持与验证代码的兼容性。在添加变量c后,它会抛出上面的错误。我可以将{"id":"123","a":"example","b":1}转换为。我无法解析{"id":"123","a":"example","b":1,"c":"ex2"}。Jackson中的objectMapper是使用自定义构造函数还是默认构造函数和setter来实现对象化。

jqjz2hbq

jqjz2hbq1#

我可能要迟到了,但这也许能帮上忙。
从2.15.2版开始,@JsonProperty可以在构造函数参数中使用,也可以在类中的随机变量中使用,但是,如果你确实在构造函数上使用@JsonCreator,那么你必须**用@JsonProperty注解构造函数参数以进行解析(* 除非你也创建了自定义解析器,但这超出了问题的范围 *)。
你也不需要在你的情况下使用TypeReference。如果你的类是用像ABC<T>这样的泛型定义的,你会想使用TypeReference。然后你会使用TypeReference<ABC<T>>
否则,您可以:objectMapper.readValue(json, ABC.class)

de90aj5v

de90aj5v2#

我刚用Jackson2.15.2运行了你的测试,它工作得很好。我可以将你的String {"id":"123","a":"example","b":1,"c":"ex2"}转换到你的ABC类中。只是我做的一些小改动--我不使用lomboc,所以我在你的类中添加了getter和setter,所有的args构造函数,没有args构造函数和toString()方法。下面是我运行的代码:

ABC abc = JsonUtils.readObjectFromJsonString("{\"id\":\"123\",\"a\":\"example\",\"b\":1,\"c\":\"ex2\"}", ABC.class);
    System.out.println(abc);

下面是输出:

ABC{id='123', number='null', a='example', b=1, c='ex2'}

只是为了澄清-类JsonUtils是一个薄 Package 器上的ObjectMapper类。这个类带有由我编写和维护的开源MgntUtils库。如果你想的话可以试试。下面是JsonUtils javadoc,该库可以作为maven artifact from Maven central或从Github获得(包括源代码和javadoc)

相关问题