用postman测试接口时,发现接口放回结果是xml格式的,而公司其他项目的接口返回结果都是json格式。出错原因如下:

一、原因
1、请求的accept字段默认是*/*,代表的匹配顺序是application/xml,application/json,text/html,因此会优先匹配xml格式。

 

2、项目中直接或间接引入了jackson-dataformat-xml这个jar包,导致项目支持输出结果为xml(原本并不支持),加上第一条原因(accept默认匹配顺序),导致输出结果优先匹配为xml格式

(例如引用Eureka或者应用Alibaba的springCloud-starter),


 
二、解决方案
1、方案一 ——在配置中指定spring的内容协商默认值(Content Negotiation 中的defaultContentType)
详见https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc#:~:text=Enabling%20Content%20Negotiation%20in%20Spring%20MVC%20Spring%20supports,can%20be%20requested%20in%20any%20of%20three%20ways

 

https://blog.csdn.net/zhanghe_zht/article/details/115008480

import org.springframework.context.annotation.Bean;
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.WebMvcConfigurationSupport;
 
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
    }
}


2、方案二——在controller层,方法前的注解中添加属性
@GetMapping(value = "/user-instance", produces = { "application/json;charset=UTF-8" })

或者:

@GetMapping(value = "/user-instance", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

以下为支持xml的配置
@GetMapping(value = "/user-instance", produces = MediaType.APPLICATION_XML_VALUE)

https://blog.csdn.net/zyb2017/article/details/80265070

3、方案三——同时支持xml和json两种配置
有时项目需求两种返回格式,这时候我们只要加上jackson xml的依赖就可以了

<dependency>
  <groupId>com.fasterxml.jackson.jaxrs</groupId>
  <artifactId>jackson-jaxrs-xml-provider</artifactId>
</dependency>


Controller在Mapping上不用标明格式

    @GetMapping(value = "/user/{id}")
//    @GetMapping(value = "/user/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public User findById(@PathVariable Long id){
        return this.restTemplate.getForObject(userServiceUrl+id,User.class);
    }


在访问时通过后缀来规定返回格式:

http://localhost:8010/user/1.json

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐