【问题标题】:Define a custom json serializer for springfox swagger2 for @ApiOperations为 @ApiOperations 定义 springfox swagger2 的自定义 json 序列化程序
【发布时间】:2017-07-10 00:06:05
【问题描述】:

我有一个简单的 rest api,实现了单个 GET 方法。我想使用 springfox 和 swagger 记录它。一切都很简单,期待示例响应。

默认情况下,springfox 使用基于反射的序列化程序 - 生成一个包含 java 类的所有公共字段的简单 json - 我想改变这种行为并使用自定义序列化程序。

这是我的控制器(为了提问,大部分代码都被简化了):

@RestController
public class Controller {

@RequestMapping( value = "/GetResponse", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.GET )
    public Response getResponse( )  {
        return Response.randomInstance();
    }

}

响应类是运行时生成的 - 我无法编辑/修改该类,因此像 @ApiModelProperty 这样的注释是不可行的。默认情况下,我使用自定义序列化程序(StaticResponseConverter 也是自动生成的):

@JsonComponent
public  class Serializer extends JsonSerializer<Response> {
    @Override
    public void serialize(Response response, JsonGenerator generator, SerializerProvider provider)
            throws IOException {
        generator.writeRaw( StaticResponseConverter.toJson(response) );
    }
}

此序列化程序在常规 api 调用中正常工作。但是,swagger2 在生成示例响应时不使用它。

招摇配置:

@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();
    }
}

我试过这种方法:

Spingfox not recognizing custom serializer when generating JSON model for swagger

也有这种方法,但是我无法将它应用到springfox。

Swagger is it possible to override custom object serialization

Maven 配置:

        <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>

在为 swagger-ui.html 生成示例响应时,如何让 springfox/swagger 使用我的自定义 json 序列化程序。

【问题讨论】:

标签: java spring-boot swagger swagger-2.0 springfox


【解决方案1】:

我支持this answer 中提供的方法通过以下方式提供模型:

  • directModelSubstitute
  • genericModelSubsitute
  • 提供替代类型规则。

它的作用是帮助 springfox 模式推理引擎解决它无法推断的问题。使用序列化程序对杰克逊来说是不透明的,因此对 springfox 也是如此。这是因为很难通过检查序列化程序的实现来了解特定类型是如何通过网络进行序列化/反序列化的。

【讨论】:

  • 不幸的是,我无法提供模型替代品,正弦响应类是运行时生成的(与 StaticResponseConverter 一起)。忘记在问题中提及,已编辑。
  • 尽管它不会用作 DTO,并且它存在的唯一目的是为响应提供架构,但您仍然应该能够创建一个代表序列化对象的虚拟类看起来像。它类似于jackson Mixin
猜你喜欢
  • 2019-05-07
  • 1970-01-01
  • 2021-09-21
  • 2011-02-25
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多