在Spring Boot中无法将ProblemHandler设置为ObjectMapper

在Spring Boot中无法将ProblemHandler设置为ObjectMapper,第1张

在Spring Boot中无法将ProblemHandler设置为ObjectMapper

无法通过或将a直接添加

DeserializationProblemHandler
到。调用构建器是不行的,因为结果对于该方法而言是本地的:Spring本身将稍后调用,从而创建另一个实例
ObjectMapper``Jackson2ObjectMapperBuilder``Jackson2ObjectMapperBuilderCustomizer``build()``ObjectMapper``build()``ObjectMapper

但是,可以通过注册Jackson模块来做到这一点:

  • 建造者有一种
    modules()
    方法
  • 该模块可通过实例访问
    setupModule()
    ,该
    SetupContext
    实例具有一个
    addDeserializationProblemHandler()
    方法

然后这应该工作

@Beanpublic 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);    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5488505.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存