jackson反序列化时忽略不需要的字段

1. xml形式

<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <!-- objectMapper配置 -->
        <property name="objectMapper">
             <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                <!--驼峰命名法转换为小写加下划线-->
                <property name="propertyNamingStrategy">
                    <bean class="com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy" />
                </property>
                <!--为null字段时不输出-->
                <property name="serializationInclusion">
                    <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                </property>
                <!--禁用空对象转换json校验-->
                <property name="configure">
                    <value type="com.fasterxml.jackson.databind.SerializationFeature">FAIL_ON_EMPTY_BEANS</value>
                </property>
                <!--忽略未知的字段-->
                <property name="configure">
                    <value type="com.fasterxml.jackson.databind.DeserializationFeature">FAIL_ON_UNKNOWN_PROPERTIES</value>
                </property>
            </bean>
        </property>
        <!-- 支持的类型,编码 -->
        <property name="supportedMediaTypes">
            <list><value>application/json;charset=UTF-8</value></list>
        </property>
    </bean>

2. Java文件如下:

@Configuration
public class MyObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = 4402127997078513582L;

    public MyObjectMapper() {
        //设置null值不参与序列化(字段不被显示)
        this.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 禁用空对象转换json校验
        this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //驼峰命名法转换为小写加下划线
        this.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    }
}

参考链接: https://blog.csdn.net/ibooks/article/details/48268183#

原文地址:https://www.cnblogs.com/Payne-SeediqBale/p/14045613.html