Swagger 2 accept xml instead of json

扶醉桌前 提交于 2019-12-04 11:19:33

You meet the problem because of the Spring MVC default get the server to render XML instead of JSON in a browser. The official document say:

To get the server to render XML instead of JSON you might have to send an Accept: text/xml header (or use a browser).

So all you need to do is make the server render JSON in browser.

When you deep into the request in browser you'll see the Request Header:

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

And if you debug into the spring boot, you will see the spring mvc will default delegate HttpMessageConverters include MappingJackson2XmlHttpMessageConverter and MappingJackson2HttpMessageConverter.

The MappingJackson2HttpMessageConverter is to render json and MappingJackson2XmlHttpMessageConverter is to render xml.

They both have a field supportedMediaTypes which means what mediatypes are supported.

The value of supportedMediaTypes in MappingJackson2HttpMessageConverter is:

The value of supportedMediaTypes in MappingJackson2XmlHttpMessageConverter is:

There is a 'text/xml;charset=UTF-8' in MappingJackson2XmlHttpMessageConverter.This is why browser render xml instend of json.

So you need add a custom MappingJackson2XmlHttpMessageConverter which support 'text/xml', for example :

    @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);
    }
}

Try this and browser will render JSON instead of XML in browser, and all things right!

What worked for me was updating the Maven dependencies for springfox-swagger2 and springfox-swagger-ui.

The newest working combination for me was:

    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.8.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!