cod*_*key 5 java json swagger jhipster springfox
我的 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>
Run Code Online (Sandbox Code Playgroud)
在我的 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);
}
Run Code Online (Sandbox Code Playgroud)
如何让 springfox 使用我的自定义序列化程序来构建我的 swagger 文档?还是我应该完全使用不同的方法?
嘿,我知道这是一个老问题,但我偶然发现了同样的问题并做了一些研究。
解决方案非常简单。编写一个代表您的自定义序列化对象的类。然后只需使用Docket 方法中的directModelSubstitute方法即可将原始模型类替换为序列化模型。
如果您的序列化程序执行类似的操作将 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);
}
Run Code Online (Sandbox Code Playgroud)
只需将此行添加.directModelSubstitute(DateTime.class, Long.class)
到您的 Docket 定义中即可。
归档时间: |
|
查看次数: |
3202 次 |
最近记录: |