使用springdoc-openapi时@RequestBody Map类型参数无法填充如何解决
解决方案
按以下步骤修改即可完成myMap参数的正常填充:
- 调整Controller方法参数与请求配置
优先用Map接口代替具体HashMap实现类作为参数类型,同时明确指定接口接收JSON格式请求:
import org.springframework.http.MediaType; @RequestMapping(value = "/process/start", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public void startProcess1( @RequestBody(description = "HashMap of strings", required = true) Map<String, String> myMap) { Assert.notEmpty(myMap, "map may not be empty"); }
- 补充Map类型的Schema适配配置
你已有的静态配置仅能让Swagger UI显示参数输入框,还需要添加自定义ModelConverter,强制Map类型请求体识别为JSON键值对结构:
import io.swagger.v3.core.converter.ModelConverter; import io.swagger.v3.core.converter.ModelConverterContext; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.lang.reflect.AnnotatedType; import java.util.Iterator; import java.util.Map; @Configuration public class SpringDocConfig { static { SpringDocUtils.getConfig().removeRequestWrapperToIgnore(java.util.Map.class); } @Bean public ModelConverter customMapModelConverter() { return new ModelConverter() { @Override public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) { if (Map.class.isAssignableFrom(type.getType())) { Schema<?> schema = new Schema<>(); schema.setType("object"); schema.setAdditionalProperties(new StringSchema()); return schema; } return chain.hasNext() ? chain.next().resolve(type, context, chain) : null; } }; } }
- 请求发送校验
调用接口时需要确保请求头Content-Type为application/json,请求体为标准JSON格式,示例:
{ "key1": "value1", "key2": "value2" }
内容的提问来源于stack exchange,提问作者user2023141
相关产品推荐
相关产品推荐

