How do you globally set Jackson to ignore unknown properties within Spring?
For jackson 1.9x or below you can ignore unknown properties with object mapper provider
@Provider
@Component
public class JerseyObjectMapperProvider implements ContextResolver<ObjectMapper> {
@Override
public ObjectMapper getContext(Class<?> type) {
ObjectMapper result = new ObjectMapper();
result.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return result;
}
}
For jackson 2.x and above you can ignore unknown properties with object mapper provider
@Provider
@Component
public class JerseyObjectMapperProvider implements ContextResolver<ObjectMapper> {
@Override
public ObjectMapper getContext(Class<?> type) {
ObjectMapper result = new ObjectMapper();
result.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return result;
}
}
Jersey classes are not auto-discovered by Spring. Have to register them manually.
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(JerseyObjectMapperProvider.class);
}
}
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>
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>
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>
For newer Jackson versions (2.x) there are a few changes:
<!-- Jackson Mapper -->
<bean id="jacksonObjectMapper" class="com.fasterxml.jackson.databind.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="com.fasterxml.jackson.databind.DeserializationFeature">FAIL_ON_UNKNOWN_PROPERTIES</value>
<value>false</value>
</list>
</property>
</bean>