你如何全球设置杰克逊忽略Spring内的未知属性? [英] How do you globally set Jackson to ignore unknown properties within Spring?

查看:455
本文介绍了你如何全球设置杰克逊忽略Spring内的未知属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Jackson有一个注释,用于忽略类中的未知属性:

Jackson has annotations for ignoring unknown properties within a class using:

@JsonIgnoreProperties(ignoreUnknown = true) 

它允许您使用此注释忽略特定属性:

It allows you to ignore a specific property using this annotation:

@JsonIgnore

如果你想全球设定你可以修改对象映射器:

If you'd like to globally set it you can modify the object mapper:

// jackson 1.9 and before
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// or jackson 2.0
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

如何使用spring全局设置它,因此可以 @Autowired 在服务器启动时没有编写其他类?

How do you set this globally using spring so it can be @Autowired at server start up without writing additional classes?

推荐答案

这可以使用spring的MethodInvokingFactoryBean实现:

This can be achieved using spring's MethodInvokingFactoryBean:

<!-- Jackson Mapper -->
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="jacksonObjectMapper" />
    <property name="targetMethod" value="configure" />
    <property name="arguments">
        <list>
            <value type="org.codehaus.jackson.map.DeserializationConfig.Feature">FAIL_ON_UNKNOWN_PROPERTIES</value>
            <value>false</value>
        </list>
    </property>
</bean>

这可以连接到RestTemplate,如下所示:

This can be wired to a RestTemplate like this:

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>
        </list>
    </property>
</bean>

它也可以直接注入到消息转换器中,以便与Spring MVC一起使用:

It can also be injected directly into the message converters for use with Spring MVC:

<mvc:annotation-driven>
    <mvc:message-converters>
        <!-- Jackson converter for HTTP messages -->
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="objectMapper" ref="jacksonObjectMapper" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

这篇关于你如何全球设置杰克逊忽略Spring内的未知属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆