java - 如何使用 SpringBoot 和 SpringFox 将声明的主体类型从 String 更改为 Swagger 中的自定义 DTO 类型

标签 java swagger swagger-ui spring-restcontroller springfox

我有一个带有一种方法的休息 Controller 。此方法采用一个注释为 @RequestBodyString 参数。由于此处未提及的某些原因,我被迫使用 String 类型并手动将其转换为 TestDTO。从 API 的使用者角度来看,主体是 TestDTO 类型,我想在 SwaggerUI 中显示此类型。

不幸的是(这是非常明显的)swagger 显示 body 是 String 类型。看下面的图片。

enter image description here

我想要实现的是在java代码中使用String主体,在swagger代码中使用TestDTO。我怎样才能强制 Swagger 显示它?我尝试查找注释及其属性,但失败了。

其余 Controller 代码如下:

@RestController
@Api(tags = { "test" }, description = "test related resources")
public class TestController {

    @Autowired
    ObjectMapper mapper;

    @RequestMapping(path = "/test", method = RequestMethod.POST)
    public void confirm(@RequestBody String requestBody) throws IOException {

        //do sth with body

        TestDTO dto = mapper.readValue(requestBody, TestDTO.class);

        //do sth with dto
    }

}

class TestDTO{

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

最佳答案

我明白了。需要进行两处更改。

首先,就像@Dave Pateral 的回答一样,必须添加@ApiImplicitParams

@RestController
@Api(tags = { "test" }, description = "test related resources")
public class TestController {

    @Autowired
    ObjectMapper mapper;

    @ApiImplicitParams({
        @ApiImplicitParam(name = "requestBody", required = true,
            dataType = "TestDTO", paramType = "body")
    })
    @RequestMapping(path = "/test", method = RequestMethod.POST)
    public void confirm(@RequestBody String requestBody) throws IOException {

        //do sth with body

        TestDTO dto = mapper.readValue(requestBody, TestDTO.class);

        //do sth with dto
    }
}

然后隐式模型必须在摘要中注册,下面是最小的工作示例

@Configuration
public class SwaggerConfiguration {

    @Autowired
    private TypeResolver typeResolver;

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
            .additionalModels(typeResolver.resolve(TestDTO.class));
    }

}

结果是 enter image description here

关于java - 如何使用 SpringBoot 和 SpringFox 将声明的主体类型从 String 更改为 Swagger 中的自定义 DTO 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56039134/

相关文章:

java - Swagger(-ui) 不显示操作

swagger - Swagger 环回模型架构中的嵌入对象

java - Spring + Swagger2 + HashMap JSON

swagger-ui - 如何在 swagger 2.0 中定义 basePath

java - 克隆一个 int[] ——有人有更快的建议吗?

java - WebDriver异常: Timed out waiting for driver server to start with phantomjs

java - 在部署中保留实体

java - Dagger + Spring

spring - 未提供 API 定义 Swagger 无法显示文档

spring-boot - 使用 Jersey 2 和 Spring Boot 向 Annotation-driven swagger.json 添加授权