我尝试使用Jackson2ObjectMapperBuilderCustomizer将自定义问题处理程序添加到对象映射器:
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
ObjectMapper m = builder.build();
m.addHandler(
new DeserializationProblemHandler() {
@Override
public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException {
System.out.println("ahahahaa");
return super.handleUnknownProperty(ctxt, p, deserializer, beanOrClass, propertyName);
}
}
);
}
};
}
但是当我自动装配ObjectMapper bean时,_problemHandlers属性为null.
我也试过用以下方法定制现有的ObjectMapper:
@Autowired
public customize(ObjectMapper mapper) {
...
}
但结果是一样的.我不知道谁可以擦除这个属性.我根本没有在另一个地方初始化对象映射器的另一个构建器/工厂/等.我做错了什么?
解决方法:
通过Jackson2ObjectMapperBuilder或Jackson2ObjectMapperBuilderCustomizer直接将DeserializationProblemHandler添加到ObjectMapper是不可能的.在构建器上调用build()是不行的,因为生成的ObjectMapper是方法的本地:Spring本身稍后将调用build(),创建另一个ObjectMapper实例.
但是,可以通过注册Jackson模块来实现:
>构建器有一个modules()方法
>模块可以通过setupModule()访问SetupContext实例,该实例具有addDeserializationProblemHandler()方法
这应该工作
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.modules(new MyModule());
}
};
}
private static class MyModule extends SimpleModule {
@Override
public void setupModule(SetupContext context) {
// Required, as documented in the Javadoc of SimpleModule
super.setupModule(context);
context.addDeserializationProblemHandler(new MyDeserializationProblemHandler());
}
}
private static class MyDeserializationProblemHandler extends DeserializationProblemHandler {
@Override
public boolean handleUnknownProperty(DeserializationContext ctxt,
JsonParser p,
JsonDeserializer<?> deserializer,
Object beanOrClass,
String propertyName)
throws IOException {
System.out.println("ahahahaa");
return super.handleUnknownProperty(ctxt, p, deserializer, beanOrClass, propertyName);
}
}