我有一个带有一种方法的休息 Controller 。此方法采用一个注释为 @RequestBody
的 String
参数。由于此处未提及的某些原因,我被迫使用 String
类型并手动将其转换为 TestDTO
。从 API 的使用者角度来看,主体是 TestDTO
类型,我想在 SwaggerUI 中显示此类型。
不幸的是(这是非常明显的)swagger 显示 body 是 String
类型。看下面的图片。
我想要实现的是在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));
}
}
关于java - 如何使用 SpringBoot 和 SpringFox 将声明的主体类型从 String 更改为 Swagger 中的自定义 DTO 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56039134/