杰克逊有一个注释,用于忽略类中的未知属性:
@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
而无需编写其他类?
答案 0 :(得分:41)
对于jackson 1.9x或更低版本,您可以使用对象映射器提供程序忽略未知属性
@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;
}
}
对于jackson 2.x及更高版本,您可以使用对象映射器提供程序忽略未知属性
@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;
}
}
Spring不会自动发现Jersey类。必须手动注册。
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(JerseyObjectMapperProvider.class);
}
}
答案 1 :(得分:19)
对于较新的Jackson版本(2.x),有一些变化:
<!-- 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>