在Spring Boot中,当JSON请求体包含目标Java对象中不存在的属性时,默认情况下Jackson会忽略这些未知属性。若希望此时抛出异常,需通过配置启用Jackson的严格反序列化模式。以下是两种实现方式:
方法1:全局配置(推荐)
在 application.properties 或 application.yml 中全局启用严格检查:
# application.properties
spring.jackson.deserialization.fail-on-unknown-properties=true
# application.yml
spring:
jackson:
deserialization:
fail-on-unknown-properties: true
方法2:通过Java配置类自定义ObjectMapper
创建配置类,手动配置ObjectMapper:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
return mapper;
}
}
方法3:注解特定类(局部配置)
若需仅为某个类启用严格检查,使用 @JsonIgnoreProperties 注解:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = false)
public class MyRequestDTO {
// 属性...
}
异常示例
启用后,若请求包含未知属性,将抛出 HttpMessageNotReadableException,并返回 400 Bad Request,错误信息示例如下:
{
"timestamp": "2023-10-05T12:34:56.789",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Unrecognized field 'unknownField' ..."
}
自定义异常处理(可选)
若需返回自定义错误响应,添加全局异常处理:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<String> handleUnknownProperties(HttpMessageNotReadableException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("请求包含非法字段: " + ex.getMessage());
}
}
总结
- 全局配置:适合统一处理所有反序列化操作。
- 注解配置:适合针对特定类灵活控制。
- 启用后,Spring Boot会在JSON包含未知属性时拒绝请求,确保数据结构的严格性。