My jhipster v2.23.1 app uses custom serializers and deserializers for JSON parsing which I register as a module in JacksonConfiguration
. The REST API works as expected using my custom mapping.
However, the JSON displayed in the auto-generated swagger documentation doesn't reflect the custom mapping. I was hoping swagger would detect custom serializers/deserializers automatically, but since it doesn't, how can I get swagger to show my custom JSON format instead of the one it detects on its own?
Based on the springfox documentation at http://springfox.github.io/springfox/docs/current/#configuring-springfox i've implemented the interface:
ApplicationListener<ObjectMapperConfigured>
in my SwaggerConfiguration bean. I can see that the onApplicationEvent(ObjectMapperConfigured event)
method is called twice. The first time the mapper will serialize my object as expected, the second time it will not. It also doesn't seem to make a difference if I register my module with the mapper or not. The object I'm working with here is a 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("[email protected]");
String contactJsonStr = null;
try {
contactJsonStr = mapper.writeValueAsString(c);
} catch(JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("Serialized Contact: " + contactJsonStr);
}
How can I get springfox to use my custom serializer in order to build my swagger documentation? Or should I be using a different approach entirely?
Hey I know this is an old question but i stumbled uppon the same problem and done a little research.
The solution is quite simple. Write a class wich represents your custom serialized object. Then just use the directModelSubstitute method in your Docket method to substitute your original model class with the serialized model.
If your serializer does something like this to serialise the DateTime into 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);
}
Just add .directModelSubstitute(DateTime.class, Long.class)
this line to your Docket definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With