【问题标题】:Spingfox not recognizing custom serializer when generating JSON model for swaggerSpingfox 在为 swagger 生成 JSON 模型时无法识别自定义序列化程序
【发布时间】:2016-02-17 03:52:56
【问题描述】:

我的 jhipster v2.23.1 应用程序使用自定义序列化器和反序列化器进行 JSON 解析,我在 JacksonConfiguration 中注册为模块。 REST API 使用我的自定义映射按预期工作。

但是,自动生成的 Swagger 文档中显示的 JSON 不反映自定义映射。我希望 swagger 会自动检测自定义序列化器/反序列化器,但既然它没有,我怎样才能让 swagger 显示我的自定义 JSON 格式而不是它自己检测到的格式?

基于http://springfox.github.io/springfox/docs/current/#configuring-springfox 的 springfox 文档,我已经实现了接口:

ApplicationListener<ObjectMapperConfigured> 

在我的 SwaggerConfiguration bean 中。我可以看到onApplicationEvent(ObjectMapperConfigured event) 方法被调用了两次。映射器第一次将按预期序列化我的对象,第二次则不会。如果我用映射器注册我的模块似乎也没有什么区别。我在这里使用的对象是一个联系人。

@Override
public void onApplicationEvent(ObjectMapperConfigured event) {
    ObjectMapper mapper = event.getObjectMapper();

    // Custom serialization for Contact objects
    SimpleModule contactModule = new SimpleModule("Contact Module");
    contactModule.addSerializer(new ContactSerializer(Contact.class));
    contactModule.addDeserializer(Contact.class, new ContactDeserializer(Contact.class));

    mapper.registerModule(contactModule);

    // My custom object
    Contact c = new Contact();
    c.setCity("Springfield");
    c.setEmail("someone@gmail.com");

    String contactJsonStr = null;
    try {
        contactJsonStr = mapper.writeValueAsString(c);
    } catch(JsonProcessingException e) {
        e.printStackTrace();
    }
    System.out.println("Serialized Contact: " + contactJsonStr);
}

如何让 springfox 使用我的自定义序列化程序来构建我的招摇文档?还是我应该完全使用不同的方法?

【问题讨论】:

标签: java json swagger jhipster springfox


【解决方案1】:

嘿,我知道这是一个老问题,但我偶然发现了同样的问题并做了一些研究。

解决方案非常简单。编写一个代表您的自定义序列化对象的类。然后只需在 Docket 方法中使用 directModelSubstitute 方法即可将原始模型类替换为序列化模型。

如果您的序列化程序执行这样的操作将 DateTime 序列化为 UNIX 时间(长)

public void serialize(final DateTime value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException, JsonProcessingException {
        long millis = value.getMillis();
        gen.writeNumber(millis);
}

只需将 .directModelSubstitute(DateTime.class, Long.class) 这一行添加到您的 Docket 定义中即可。

【讨论】:

    猜你喜欢
    • 2016-02-29
    • 2014-10-05
    • 1970-01-01
    • 2020-12-09
    • 2011-11-12
    • 2018-02-04
    • 2014-05-18
    • 2013-09-30
    • 1970-01-01
    相关资源
    最近更新 更多