繁体   English   中英

Java 如何创建一个模块 class 扩展 SimpleModule 以用于 addDeserializer?

[英]Java How do I create a module class that extends SimpleModule for addDeserializer?

目前,我正在使用自定义 JsonDeserialize class 注册我的 class 并在我的应用程序启动中声明一个新的 SimpleModule,例如

public static void configure(ObjectMapperModule mapper) {
  SimpleModule module = new SimpleModule();
  module.addDeserializer(LocalFile.class, new LocalFileDeserializer());
  // module add more deserializer class
  mapper.registerModule(module);
}

无论如何我可以创建一个扩展 SimpleModule 的 class,所以我可以在构造函数中注册所有 class 吗? 我在下面尝试过,但失败了,

public class MyCustomModule extends SimpleModule {
    private static final SimpleModule module = new SimpleModule();

    public MyCustomModule() {
        initMyCustomModule();
    }

    final void initMyCustomModule() {
        module.addDeserializer(LocalFile.class, new LocalFileDeserializer());
    }
}

// In app start
mapper.registerModule(new MyCustomModule());

I have seen the initMyCustomModule was being called during app start but my deserialize class was not being called when tried to deserialize my object from request, I was thinking because I should register the module inside my class, eg: mapper.registerModule(new MyCustomModule( )。模块)? 我还注意到有一个覆盖方法

@Override
public void setupModule(SetupContext context)

但我不知道如何使用它将addDeserializer到上下文中......

似乎这样可行...我不需要声明 SimpleModule 的新实例并在构造函数中使用它,我可以直接在构造函数中使用addDeserializer ..

public class MyCustomModule extends SimpleModule {
    public MyCustomModule() {
        initMyCustomModule();
    }

    final void initMyCustomModule() {
        addDeserializer(LocalFile.class, new LocalFileDeserializer());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM