java – Swagger 2接受xml而不是json

我有一个带有
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

在招摇的UI中,它工作正常.但是当我在浏览器中直接尝试此链接时,出现此错误:
《java – Swagger 2接受xml而不是json》

使用Firebug,我发现它接受XML内容而不是JSON内容.
《java – Swagger 2接受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.

当您深入了解浏览器中的请求时,您将看到请求标头:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

如果你调试到spring boot,你会看到spring mvc将默认委托HttpMessageConverters包括MappingJackson2XmlHttpMessageConverter和MappingJackson2HttpMessageConverter.

MappingJackson2HttpMessageConverter用于渲染json,MappingJackson2XmlHttpMessageConverter用于渲染xml.

它们都有一个字段supportedMediaTypes,这意味着支持哪种mediatype.

MappingJackson2HttpMessageConverter中supportedMediaTypes的值为:

《java – Swagger 2接受xml而不是json》

MappingJackson2XmlHttpMessageConverter中supportedMediaTypes的值为:

《java – Swagger 2接受xml而不是json》

MappingJackson2XmlHttpMessageConverter中有一个’text / xml; charset = UTF-8′.这就是为什么浏览器渲染xml的json.

所以你需要添加一个支持’text / xml’的自定义MappingJackson2XmlHttpMessageConverter,例如:

    @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,一切正常!

点赞