springboot/cloud项目接口调用返回结果从json变为xml原因

用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的内容协商默认值( 中的defaultContentType)

详见

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)

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
经验分享 程序员 微信小程序 职场和发展