Jackson 反序列化 - 错误 body 类型成功反序列化

Jackson Deserialization - Wrong body types sucessfully deserializing

我正在尝试验证对我的 REST 控制器的 POST 请求,在我的 DTO class:

上有一些属性和验证

EmployeeDTOInput.java

@Getter
@Setter
public class EmployeeDTOInput {

  @NotBlank("name must not be blank!")
  private String name;

  @DecimalMin(value = "0.01", message = "salary must be greather than or equal to [=11=].01!")
  private BigDecimal salary;

  @NotNull("commission elegible must not be null!")
  private boolean commissionElegible;
}

此外,控制器上有一个有效的检查器:

@PostMapping
public EmployeeDTO store(@RequestBody @Valid EmployeeDTOInput employeeDTOInput) {
 // Controller logic
}

写了一些测试,我想通了,如果我的 JSON 请求 object 有这个语法,并且它工作正常:

{
  name: 12345,
  salary: "30000.50"
}

有没有办法拒绝这种请求,我的意思是,根据实际的DTO属性,只接受JSON 属性类型的100%一致性,只接受float格式salary,字符串格式为 name 并且不忽略 commissionElegible?

我尝试在 application.properties 上添加一些 Jackson 属性:

spring.jackson.deserialization.fail-on-unknown-properties=true
spring.jackson.deserialization.fail-on-ignored-properties=true
spring.jackson.deserialization.fail-on-invalid-subtype=true

以及 DTO 上的一些 Jackson 注释 class:

@Getter
@Setter
public class EmployeeDTOInput {

  @JsonFormat(shape = JsonFormat.Shape.STRING)
  @NotBlank("name must not be blank!")
  private String name;
  
  @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT)
  @DecimalMin(value = "0.01", message = "salary must be greather than or equal to [=15=].01!")
  private BigDecimal salary;

  @JsonFormat(shape = JsonFormat.Shape.BOOLEAN)
  @NotNull("commission elegible must not be null!")
  private boolean commissionElegible;
}

但请求仍然有效。

有什么方法可以防止这种 'wrong' 反序列化并将其配置为抛出异常吗?

我认为您需要配置 ObjectMapper ALLOW_COERCION_OF_SCALARS 属性。

可以通过更改application.properties中的设置来实现:

spring.jackson.mapper.allow-coercion-of-scalars=false

这是 JavaDoc:

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/MapperFeature.html#ALLOW_COERCION_OF_SCALARS