我的 jhipster v2.23.1 应用程序使用自定义序列化器和反序列化器进行 JSON 解析,我将其注册为模块JacksonConfiguration
。 REST API 使用我的自定义映射按预期工作。
但是,自动生成的 swagger 文档中显示的 JSON 并不反映自定义映射。我希望 swagger 能够自动检测自定义序列化器/反序列化器,但既然它不能,我怎样才能让 swagger 显示我的自定义 JSON 格式而不是它自己检测到的格式?
基于 springfox 文档http://springfox.github.io/springfox/docs/current/#configuring-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("[email protected]");
String contactJsonStr = null;
try {
contactJsonStr = mapper.writeValueAsString(c);
} catch(JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("Serialized Contact: " + contactJsonStr);
}
如何让 springfox 使用自定义序列化器来构建我的 swagger 文档?或者我应该使用完全不同的方法?
嘿,我知道这是一个老问题,但我偶然发现了同样的问题并做了一些研究。
解决方案非常简单。编写一个代表您的自定义序列化对象的类。然后只需使用直接模型替代Docket 方法中的方法,用序列化模型替换原始模型类。
如果您的序列化程序执行类似的操作将 DateTime 序列化为 UNIX Time (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 定义中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)