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

本文探讨了使用Postman测试接口时返回XML格式而非期望的JSON格式的问题,并提供了三种解决方案,包括修改配置文件、调整Controller层注解及引入依赖。

用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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值