使用 @RequestBody 接收 JSON 時,若請求體包含實體類中不存在的字段,Jackson 默認拋出 UnrecognizedPropertyException: Unrecognized field "xxx", not marked as ignorable。本文提供三種解決方案。
MappingJacksonHttpMessageConverter 使用 Jackson 反序列化,默認要求 JSON 字段與 Java Bean 屬性完全匹配。多餘字段導致異常。
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
private String name;
private String password;
// getter/setter
}
或指定忽略特定字段:
@JsonIgnoreProperties({"internalId", "secretKey"})
public class User { ... }
調整前端序列化邏輯,僅發送後端需要的字段,減少網絡傳輸量,從源頭避免問題。
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
}
同一請求中多次使用 @RequestBody 會報 Stream closed,因 HttpServletRequest.getInputStream() 只能讀取一次。解決:使用 Filter 緩存請求體(如 ContentCachingRequestWrapper)或改用 @RequestParam 接收表單數據。
最佳實踐: 實體類加
@JsonIgnoreProperties(ignoreUnknown = true)兼容性最好,不影響現有字段綁定,且無需全局配置副作用。