如何解决Swagger2 map集合返回报错
时间: 2024-02-12 07:55:06 浏览: 69
Swagger2默认不支持Map集合的返回,需要自定义配置来解决这个问题。
可以在Swagger2的配置文件中添加一个自定义的Docket Bean,并在该Bean中添加一个自定义的ModelBuilderPlugin,用于处理Map集合的返回值。具体代码如下:
```
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.apiInfo(apiInfo())
.extensions(Collections.singletonList(new MapModelBuilderPlugin()));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("API")
.description("API reference for developers")
.termsOfServiceUrl("http://localhost:8080/")
.contact(new Contact("Developers", "http://localhost:8080/", ""))
.license("Apache License Version 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0")
.version("2.0")
.build();
}
private static class MapModelBuilderPlugin implements ModelBuilderPlugin {
@Override
public boolean supports(DocumentationType delimiter) {
return true;
}
@Override
public void apply(ModelContext modelContext) {
ResolvedType type = modelContext.getTypeResolver().resolve(Map.class, WildcardType.class);
if (type != null) {
ModelReference ref = modelContext.getResolver().resolve(Map.class, WildcardType.class, modelContext.getAlternateTypeProvider());
ModelImpl model = new ModelImpl().type(type);
modelContext.getDocumentationType().getModelNames().add(ref.getType().getErasedType().getSimpleName());
modelContext.getAdditionalModels().add(ref.getType().getErasedType(), model);
}
}
}
}
```
其中,MapModelBuilderPlugin用于处理Map集合的返回值,将Map类型转换成ModelImpl类型。在Docket Bean中添加该插件即可解决Map集合返回的问题。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)