首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

解決 SpringMVC @RequestBody 反序列化報錯:Unrecognized field not marked as ignorable

     編輯:Java 綜合教學

解決 SpringMVC @RequestBody 反序列化報錯:Unrecognized field not marked as ignorable

使用 @RequestBody 接收 JSON 時,若請求體包含實體類中不存在的字段,Jackson 默認拋出 UnrecognizedPropertyException: Unrecognized field "xxx", not marked as ignorable。本文提供三種解決方案。

問題根因

MappingJacksonHttpMessageConverter 使用 Jackson 反序列化,默認要求 JSON 字段與 Java Bean 屬性完全匹配。多餘字段導致異常。

方案一:實體類添加 @JsonIgnoreProperties 忽略未知字段(推薦)

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    private String name;
    private String password;
    // getter/setter
}

或指定忽略特定字段:

@JsonIgnoreProperties({"internalId", "secretKey"})
public class User { ... }

方案二:前端發送前過濾多餘字段

調整前端序列化邏輯,僅發送後端需要的字段,減少網絡傳輸量,從源頭避免問題。

方案三:全局配置 ObjectMapper(Spring Boot 2.x+)

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }
}

補充:@RequestBody 多次讀取流關閉問題

同一請求中多次使用 @RequestBody 會報 Stream closed,因 HttpServletRequest.getInputStream() 只能讀取一次。解決:使用 Filter 緩存請求體(如 ContentCachingRequestWrapper)或改用 @RequestParam 接收表單數據。

最佳實踐: 實體類加 @JsonIgnoreProperties(ignoreUnknown = true) 兼容性最好,不影響現有字段綁定,且無需全局配置副作用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved