我的 jhipster v2.23.1 应用使用自定义序列化器和反序列化器进行 JSON 解析,我在 JacksonConfiguration
中注册为一个模块。 REST API 使用我的自定义映射按预期工作。
但是,自动生成的 swagger 文档中显示的 JSON 不反射(reflect)自定义映射。我希望 swagger 会自动检测自定义序列化器/反序列化器,但既然它没有,我如何让 swagger 显示我的自定义 JSON 格式而不是它自己检测到的格式?
基于 http://springfox.github.io/springfox/docs/current/#configuring-springfox 处的 springfox 文档我已经实现了接口(interface):
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 使用我的自定义序列化器来构建我的 swagger 文档?或者我应该完全使用不同的方法吗?
最佳答案
嘿,我知道这是一个老问题,但我偶然发现了同样的问题并做了一些研究。
解决方案非常简单。编写一个代表您的自定义序列化对象的类。然后只需使用 directModelSubstitute Docket 方法中的方法用序列化模型替换原始模型类。
如果您的序列化器执行类似这样的操作将 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 定义中。
关于java - Spingfox 在为 swagger 生成 JSON 模型时无法识别自定义序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33728778/