配置Dropwizard ObjectMapper以进行配置以忽略未知



使用ObjectMapper(com.fasterxml.jackson.databind),可以指定它应该忽略未知属性。这可以通过在类级别添加@JsonIgnoreProperties(ignoreUnknown = true)或在映射器中将其设置为默认行为来完成。但是,当以initialize()Application<MyConfiguration>方法执行此操作时,它似乎没有效果。

ObjectMapper mapper = bootstrap.getObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

对于配置文件中的未知属性,它仍然失败。如何配置Dropwizard以忽略未知属性?

bootstrap.getObjectMapper()配置DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES没有达到预期效果的原因是ConfigurationFactory(稍后用于解析配置的类)在其构造函数中启用了对象映射器的特定功能(请参阅此处):

public ConfigurationFactory(Class<T> klass,
Validator validator,
ObjectMapper objectMapper,
String propertyPrefix) {
...
this.mapper = objectMapper.copy();
mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
...
}

无法直接更改ConfigurationFactory的行为,但 Dropwizard 提供了通过Boostrap.setConfigurationFactoryFactory()覆盖创建它的工厂的方法,ConfigurationFactoryFactory。这允许将实际ObjectMapper替换为不允许覆盖配置并将其传递给ConfigurationFactory的代理:

bootstrap.setConfigurationFactoryFactory(
(klass, validator, objectMapper, propertyPrefix) -> {
return new ConfigurationFactory<>(klass, validator,
new ObjectMapperProxy(objectMapper), propertyPrefix);
}
);

忽略尝试启用ObjectMapperProxy的代码FAIL_ON_UNKNOWN_PROPERTIES下面:

private static class ObjectMapperProxy extends ObjectMapper {
private ObjectMapperProxy(ObjectMapper objectMapper) {
super(objectMapper);
}
private ObjectMapperProxy(ObjectMapperProxy proxy) {
super(proxy);
}
@Override
public ObjectMapper enable(DeserializationFeature feature) {
// do not allow Dropwizard to enable the feature
if (!feature.equals(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
super.enable(feature);
}
return this;
}
@Override
public ObjectMapper copy() {
return new ObjectMapperProxy(this);
}
}

请注意,除了覆盖跳过enable之外,还实现了FAIL_ON_UNKNOWN_PROPERTIEScopy(与其他构造函数一起),因为ConfigurationFactory需要对象映射器支持复制。

虽然上面的解决方案有效,但它显然是一种解决方法,我建议升级到更新的 Dropwizard 版本。新的 Dropwizard 使ObjectMapper配置更易于覆盖(例如,请参阅 Dropwizard 1.1.x 中提供的此 Dropwizard 提交)。

您需要通过以下方式禁用该功能:

bootstrap.getObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

更新:功能禁用适用于 API 资源,但不适用于配置 YAML。相反,您需要将下面的注释(与问题中提到的注释相同)添加到配置类中:

@JsonIgnoreProperties(ignoreUnknown = true)

最新更新