Jackson有一个忽略类中未知属性的注释:
@JsonIgnoreProperties(ignoreUnknown = true)
它允许您使用此注释忽略特定的属性:
@JsonIgnore
如果你想全局设置它,你可以修改对象映射器:
// 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不写额外的类?
这可以使用spring的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像这样:
<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:
<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>