I have a simple rest api, with single GET method implemented. I would like to have it documented using springfox and swagger. All is very easy expect sample response.
By default springfox uses reflection based serializer - produces a simple json with all public fields of java class - I would like to change this behavior and use custom serializer.
Here is my controller (most of the code is simplified for the sake of the question):
@RestController
public class Controller {
@RequestMapping( value = "/GetResponse", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.GET )
public Response getResponse( ) {
return Response.randomInstance();
}
}
Response class is runtime generated - I cannot edit/modify that class, so annotations like @ApiModelProperty are not feasible. By default I use custom serializer (StaticResponseConverter is also auto generated):
@JsonComponent
public class Serializer extends JsonSerializer<Response> {
@Override
public void serialize(Response response, JsonGenerator generator, SerializerProvider provider)
throws IOException {
generator.writeRaw( StaticResponseConverter.toJson(response) );
}
}
This serializer works without issues for regular api calls. However, it is not used by swagger2 when producing a sample response.
Swagger config:
@Configuration
@EnableSwagger2
public class SwaggerConfig
{
@Bean
public Docket api()
{
return new Docket( DocumentationType.SWAGGER_2 ).select()
.apis( x -> x.declaringClass().equals( Controller.class ) ).paths( PathSelectors.any() )
.build();
}
}
I tried this approach:
Spingfox not recognizing custom serializer when generating JSON model for swagger
There is also this approach, but I'm unable to apply it to springfox.
Swagger is it possible to override custom object serialization
Maven config:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
How to make springfox/swagger to use my custom json serializer when generating sample response for swagger-ui.html.