引言
在测试spring boot 的post传递实体类的过程中发现了一个反向序列化的异常。
异常
JSON parse error: Cannot construct instance of `com.**` (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.**` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (PushbackInputStream); line: 2, column: 2]]
解决方案
在实体类中添加无参构造函数。
原因
jackson的反序列化需要无参构造函数,而我在实体类中添加了有参数的构造函数。
在实体类中添加无参构造函数即可。
修改前
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName("user")
public class User implements Serializable {
@TableId("id")
private String id;
@TableField("user_id")
private String userId;
@TableField("device_id")
private String deviceId;
public User(String deviceId) {
this.deviceId= deviceId;
}
}
修改后
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName("user")
public class User implements Serializable {
@TableId("id")
private String id;
@TableField("user_id")
private String userId;
@TableField("device_id")
private String deviceId;
public User() {
super();
}
public User(String deviceId) {
this.deviceId= deviceId;
}
}