Java 为springfox swagger2为@ApiOperations定义自定义json序列化程序

Java 为springfox swagger2为@ApiOperations定义自定义json序列化程序,java,spring-boot,swagger,swagger-2.0,springfox,Java,Spring Boot,Swagger,Swagger 2.0,Springfox,我有一个简单的RESTAPI,实现了单GET方法。我想用springfox和swagger来记录它。所有这些都很容易,希望得到样本响应 默认情况下,springfox使用基于反射的序列化程序-生成包含java类的所有公共字段的简单json-我想更改此行为并使用自定义序列化程序 这是我的控制器(为了回答这个问题,大部分代码都被简化了): 响应类是运行时生成的-我无法编辑/修改该类,因此像@ApiModelProperty这样的注释是不可行的。默认情况下,我使用自定义序列化程序(StaticResp

我有一个简单的RESTAPI,实现了单GET方法。我想用springfox和swagger来记录它。所有这些都很容易,希望得到样本响应

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

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

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

我尝试过这种方法:

也有这种方法,但我无法将其应用于springfox

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>

伊奥·斯普林福克斯
springfox-Swagger 2
2.6.1
伊奥·斯普林福克斯
springfox招摇过市用户界面
2.6.1

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

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

  • a
    directModelSubstitute
  • a
    genericModelSubstitute
  • 提供备用类型规则

这有助于springfox模式推理引擎推断出它无法推断的内容。使用序列化程序对jackson来说是不透明的,因此对springfox也是如此。这是因为通过检查序列化程序的实现,很难知道特定类型是如何通过线路序列化/反序列化的。

我支持中提供的方法。不幸的是,我无法提供模型替代,sine Response类是运行时生成的(与StaticResponseConverter一起)。在问题中忘了提到它,edited。假定它不会用作DTO,并且它存在的唯一目的是为响应提供模式,那么您应该仍然能够创建一个表示序列化对象外观的伪类。它类似于
@JsonComponent
public  class Serializer extends JsonSerializer<Response> {
    @Override
    public void serialize(Response response, JsonGenerator generator, SerializerProvider provider)
            throws IOException {
        generator.writeRaw( StaticResponseConverter.toJson(response) );
    }
}
@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();
    }
}
        <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>