Spingfox在生成Swagger的JSON模型时无法识别自定义序列化程序。

5
我的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)方法被调用了两次。第一次,映射器会按预期对我的对象进行序列化,第二次则不会。似乎注册模块与否也没有影响。我正在处理的对象是一个联系人(Contact)。
@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使用我的自定义序列化器来构建Swagger文档?或者我应该采用完全不同的方法吗?

你应该询问Springfox项目。 - Gaël Marziou
@GaëlMarziou 这个问题已经被问了两次,但是还没有任何处理措施,https://github.com/swagger-api/swagger-core/issues/1753 https://github.com/springfox/springfox/issues/1639 - DaithiG
那么你应该为它做出贡献。 - Gaël Marziou
1个回答

3

嘿,我知道这是一个老问题,但我遇到了同样的问题并进行了一些研究。

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

如果您的序列化程序将DateTime序列化为UNIX时间(Long):

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定义中即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接