@RestController注解,对于返回值是集合类的API接口,其数据还是会被系列化成XML格式

问题@RestController注解,对于返回值是集合类的API接口,其数据还是会被系列化成XML格式

排查原因

经过排查发现是spring-cloud-starter-netflix-eureka-client的Maven依赖间接引入了jackson-dataformat-xml包,而如果Spring的http消息转换器(HttpMessageConverter)使用了该包会,那么它会根据http请求头上的Accept来决定返回XML还是JSON。然而目前大多数浏览器在没有额外设置的情况下,默认的Accept值都是"text/html,application/xhtml+xml,application/xml",这就使得直接在浏览地址栏访问接口时,我们心里预期要返回JSON的返回了XML,因为JSON和XML格式是可以互转的!

解决方案

第一种是:如果你的应用不会再需要返回xml的系列化格式,那么直接在pom.xml文件中将jackson-dataformat-xml这外包排除即可(如果其他包也进行了jackson-dataformat-xml的依赖引用也要视情况排除):
<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.3.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.jackson.dataformat</groupId>
                    <artifactId>jackson-dataformat-xml</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
第二种是:不排除jackson-dataformat-xml包,而是直接在相应接口方法或Controller上明确指定将返回JSON格式的值:

    @GetMapping(value = "/user-instance", produces = MediaType.APPLICATION_PROBLEM_JSON_VALUE)
    public List<ServiceInstance> showUserServiceInfo() {
        return this.discoveryClient.getInstances("provider-user-metadata");
    }
第三种:还可以通过添加自定义的Spring的http消息转换器(HttpMessageConverter)的方法来定制返回值的系列化,方法就是实现WebMvcConfigurer,并重写configureMessageConverters方法,例如换用阿里的Fastjson来做http消息转换:
/**
     * 消息转换器自定义配置,向当前的Http消息转换器列表增加阿里云的FastJson消息转换器
     *
     * @param converters 当前的Http消息转换器列表对象
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonConfig.setCharset(Charset.forName("GB2312"));//解决中文系列化后成乱码
        fastJsonConverter.setFastJsonConfig(fastJsonConfig);
        //converters.add(fastJsonConverter);//这会让fastJsonConverter排在消息转换器管道列表的最后,可能会轮不到它处理消息转换
        converters.add(0, fastJsonConverter);//要显示指明将fastJsonConverter排在消息转换器管道列表的首位
    }
导包:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>

参考:https://www.cnblogs.com/xuruiming/p/13283288.html

原文地址:https://www.cnblogs.com/staystand/p/14790854.html