You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringMVC反序列化时忽略未知属性的全局配置方法咨询

问题解答

Spring MVC 3.2.15.RELEASE 版本没有内置类似Spring Boot的一键配置项,你可以通过全局配置Jackson消息转换器的方式实现相同效果,共有两种常见配置方案:

方案1:XML配置形式(适用于XML配置的Spring MVC项目)

在Spring MVC的配置文件中自定义MappingJackson2HttpMessageConverter,并修改其内部ObjectMapper的反序列化规则:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="configure">
                        <array>
                            <value type="com.fasterxml.jackson.databind.DeserializationFeature">FAIL_ON_UNKNOWN_PROPERTIES</value>
                            <value type="java.lang.Boolean">false</value>
                        </array>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

方案2:JavaConfig配置形式(适用于注解配置的Spring MVC项目)

继承WebMvcConfigurerAdapter重写消息转换器配置方法:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper objectMapper = new ObjectMapper();
        // 关闭未知属性反序列化失败开关
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
        converters.add(jsonConverter);
    }
}

注意事项

  • 上述配置仅对Jackson 2.x版本生效,如果你项目中使用的是Jackson 1.x老版本,需要替换为MappingJacksonHttpMessageConverter,对应配置org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES属性即可
  • 如果你只需要对部分类做忽略未知属性处理,可以直接在对应类上添加@JsonIgnoreProperties(ignoreUnknown = true)注解,不需要全局配置

内容的提问来源于stack exchange,提问作者bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:09:03