如何将Swagger中Spring Boot POST接口默认响应媒体类型设为JSON?
Spring Boot接口默认响应媒体类型改为JSON的实现方案
方法一:调整接口注解的produces顺序
Spring在客户端未指定Accept请求头时,会优先选择produces数组中第一个声明的媒体类型。只需把APPLICATION_JSON_VALUE放在数组首位即可:
@PostMapping( consumes = { APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE }, produces = { APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE } // JSON在前,作为默认响应类型 ) public Game create( @Valid @RequestBody Game request, BindingResult bindingResult ) { // 业务逻辑实现 }
这个改动同时会让Swagger文档里的默认media-type选项变为JSON,匹配你的需求。
方法二:全局配置默认响应类型
如果希望整个应用的所有接口都默认返回JSON,可创建WebMvc配置类,全局设置内容协商规则:
import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcContentConfig implements WebMvcConfigurer { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { // 设置默认响应类型为JSON configurer.defaultContentType(MediaType.APPLICATION_JSON) // 保留对JSON和XML格式的支持 .mediaType("json", MediaType.APPLICATION_JSON) .mediaType("xml", MediaType.APPLICATION_XML); } }
该配置生效后,所有未指定Accept头的请求都会默认返回JSON,同时不影响客户端指定Accept: application/xml获取XML格式响应。
内容的提问来源于stack exchange,提问作者JamesWillett
相关产品推荐
相关产品推荐

