You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot修改配置后接口返回XML如何恢复为JSON响应

问题根因

Spring Boot 基于内容协商机制决定接口返回的响应格式:

  • 默认情况下项目仅引入JSON序列化依赖jackson-databind,因此接口默认返回JSON
  • 当classpath中存在jackson-dataformat-xml依赖时,Spring Boot会自动注册XML消息转换器。如果修改配置时设置了默认返回格式为XML、或者请求Accept头优先匹配XML、或者依赖传递引入了该XML包,都会导致接口返回XML格式响应。
  • 微服务场景下也可能是Spring Cloud Gateway转发时修改了请求Accept头,触发后端返回XML。

解决方法

方法一:单个接口指定返回JSON(最快生效)

在Controller接口的@GetMapping注解中添加produces属性指定返回格式为JSON,修改代码如下:

@GetMapping(value = "/getAll", produces = "application/json")
public List<Country> getAll() {
    return countryService.getAllCountries();
}

@GetMapping(value = "/{country}", produces = "application/json")
public Country getCountry(@PathVariable String country) {
    return countryService.getCountry(country);
}

该配置优先级最高,不受全局配置或请求头影响。

方法二:全局配置默认返回JSON

在application.properties中添加以下全局内容协商配置:

# 设置默认返回格式为JSON
spring.mvc.contentnegotiation.default-content-type=application/json
# 关闭根据路径后缀判定返回格式的逻辑,避免.xml后缀触发XML返回
spring.mvc.contentnegotiation.favor-path-extension=false
# 关闭根据请求参数判定返回格式的逻辑
spring.mvc.contentnegotiation.favor-parameter=false

配置后所有接口默认返回JSON,无需修改业务代码。

方法三:彻底禁用XML响应

如果项目完全不需要XML格式支持,直接从依赖中排除jackson-dataformat-xml即可。如果是传递依赖引入的包,Maven项目可在对应依赖下添加排除规则:

<exclusions>
    <exclusion>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
    </exclusion>
</exclusions>

移除该依赖后,Spring Boot不会注册XML消息转换器,所有接口只会返回JSON格式。

微服务场景额外检查

如果以上配置不生效,检查Spring Cloud Gateway的转发规则,确认没有修改请求的Accept头为application/xml,如果有相关配置调整为支持application/json即可。

内容的提问来源于stack exchange,提问作者Sreya Salil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:06:04