2025年7月工作经验记录

1 Jackson反序列化问题

遇到了这样的问题:

1
2
3
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class com.caacsri.route.domain.vo.RouteBindingVO]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of com.xxx.route.domain.vo.RouteBindingVO (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.xxx.route.domain.vo.RouteBindingVO` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

相关代码:

1
2
3
4
5
6
@PostMapping("/updateBinding")
public AjaxResult updateBinding(
@RequestBody RouteBindingVO routeBindingVO
) {
return AjaxResult.success(airportRoutePlanService.updateBinding(routeBindingVO));
}
1
2
3
4
5
6
7
@AllArgsConstructor // 只有全参构造器
@Data
public class RouteBindingVO {
private String callSign;

private String routeId;
}

原因:

  1. @RequestBody 默认使用 Jackson 进行 JSON 反序列化;
  2. Jackson 进行 JSON 反序列化时需要无参构造器,步骤:
    1. 通过无参构造器 new 一个对象实例;
    2. 用反射设置每个字段的值(或通过 setter 方法);

修改:提供无参构造器

1
2
3
4
5
6
7
8
@AllArgsConstructor // 只有全参构造器
@NoArgsConstructor // 提供无参构造器
@Data
public class RouteBindingVO {
private String callSign;

private String routeId;
}

或者使用 @JsonCreator + @JsonProperty,告诉 Jackson 用某个有参构造器

1
2
3
4
5
6
@JsonCreator
public RouteBindingVO(@JsonProperty("callSign") String callSign,
@JsonProperty("routeId") String routeId) {
this.callSign = callSign;
this.routeId = routeId;
}