【已解决】cannot deserialize from Object value 异常

零、参考文献

关于 cannot deserialize from Object value (no delegate- or property-based Creator)的错误,解决方法。

一、写在前面

最近写一个小游戏,需要服务端向匹配端发送Json数据,业务端需要向服务端用RestTemplate发送Post请求,且数据为JSON格式时的请求方式,但是接收数据时出现了反序列化异常,现记录解决方法,异常如下:

二、问题场景

请求时的反序列化异常,具体报错如下:

Resolved[org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.kob.common.request.MatchingRequest` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.kob.common.request.MatchingRequest` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)at [Source: (PushbackInputStream); line: 1, column: 2]]

看了一下,异常描述为: (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator),即 (尽管至少存在一创建者):不能从 Object 值反序列化(没有基于委托或属性的 创建者)

也就是说,不能反序列化,看了一下接收请求的实体类,发现没有无参构造方法

三、场景重现

服务端代码:

接收参数的实体类


@Data  
@AllArgsConstructor  
public class MatchingRequest {  
  
   private int userId;  
  
   private int rating;  
  
   public MatchingRequest(int userId) {  
      this.userId = userId;  
   }  
}

其余代码详见:RestTemplate发送数据为JSON的Post请求

四、解决方案

接收参数的实体类添加无参构造方法即可

  
@Data  
@AllArgsConstructor  
@NoArgsConstructor  // 避免反序列化异常
public class MatchingRequest {  
  
   private int userId;  
  
   private int rating;  
  
   public MatchingRequest(int userId) {  
      this.userId = userId;  
   }  
   
}

五、总结反思

  1. 反序列化要使用无参构造函数
  2. 全参构造会覆盖掉默认的无参构造,导致没有无参构造方法,无法反序列化

六、写在后面

欢迎关注,实现期间会经常记录一些项目实践中遇到的问题。

欢迎随时留言讨论,与君共勉,知无不答!

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值