您如何全局设置 Jackson 以忽略 Spring 中的未知属性? [英] How do you globally set Jackson to ignore unknown properties within 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>
这篇关于您如何全局设置 Jackson 以忽略 Spring 中的未知属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!