我有一个带有 spring boot 的项目,我想使用 swagger2 来记录我的 json web 服务。
我有这样的配置:
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket welcomeMessageApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My API")
.description("Lorem Ipsum is simply dummy text of ...")
.termsOfServiceUrl("an url")
.contact("contact")
.license("")
.licenseUrl("")
.version("2.0")
.build();
}
要阅读文档,我使用此链接:http://localhost:9081/v2/api-docs
在 swagger UI 中,它工作正常。但是当我直接在我的浏览器中尝试这个链接时,我有这个错误:
使用 Firebug,我看到它接受 XML 内容而不是 JSON 内容。
如何修改 swagger 配置以接受 JSON 内容?
最佳答案
您遇到问题是因为 Spring MVC 默认让服务器在浏览器中呈现 XML 而不是 JSON。 The official document说:
To get the server to render XML instead of JSON you might have to send an Accept: text/xml header (or use a browser).
所以您需要做的就是让服务器在浏览器中呈现 JSON。
当您深入浏览器中的请求时,您会看到请求 header :
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
如果你调试到 spring boot,你会看到 spring mvc 将默认委托(delegate) HttpMessageConverters
包括 MappingJackson2XmlHttpMessageConverter
和 MappingJackson2HttpMessageConverter
.
MappingJackson2HttpMessageConverter
是渲染json和MappingJackson2XmlHttpMessageConverter
就是渲染xml。
他们都有一个字段supportedMediaTypes
这意味着支持哪些媒体类型。
supportedMediaTypes
的值在MappingJackson2HttpMessageConverter
是:
supportedMediaTypes
的值在MappingJackson2XmlHttpMessageConverter
是:
MappingJackson2XmlHttpMessageConverter
中有一个'text/xml;charset=UTF-8' .这就是浏览器呈现 xml 而不是 json 的原因。
所以你需要添加一个自定义 MappingJackson2XmlHttpMessageConverter
支持 'text/xml',例如:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
List<MediaType> list = new ArrayList<>();
list.add(MediaType.APPLICATION_JSON_UTF8);
list.add(new MediaType("text", "html", Charset.forName("UTF-8")));
list.add(new MediaType("application", "*+json", Charset.forName("UTF-8")));
converter.setSupportedMediaTypes(list);
converters.add(converter);
}
}
试试这个,浏览器将在浏览器中呈现 JSON 而不是 XML,一切正常!
关于java - Swagger 2 接受 xml 而不是 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33211610/