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

Spring MVC返回基本类型时Content-Type为application/json的疑问

Spring MVC返回基本类型时Content-Type为application/json的困惑与解决方案

问题描述

在Spring MVC中返回基本类型(如boolean)或其包装类(如Boolean)时,响应的Content-Type为application/json,这与预期的text/plain不符。但返回String类型时,Content-Type却是text/plain;charset=UTF-8,因此认为基本类型也应默认使用text/plain类型,想确认该期望是否合理,同时希望Spring MVC能默认提供对应转换器,而非必须自定义。

示例代码

@SpringBootApplication
public class SpringConverterApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringConverterApplication.class, args);
  }

}

@RestController
@RequestMapping("/demo")
class DemoController {

  @GetMapping("/b1")
  public boolean bool() {
    return true;
  }

  @GetMapping("/b2")
  public Boolean boolW() {
    return Boolean.FALSE;
  }
}

原因分析

  • Spring MVC对String类型做了特殊处理,由StringHttpMessageConverter负责,默认设置text/plain的Content-Type。
  • 基本类型及其包装类默认由Jackson的MappingJackson2HttpMessageConverter处理,该转换器默认输出JSON格式,因此Content-Type为application/json。这是Spring的默认设计,旨在统一非String简单类型的序列化格式。

合理性说明

这种期望有一定合理性:基本类型返回值本质是简单字面量,用text/plain更直观。但Spring的默认设计倾向于保持类型序列化的一致性,比如数字、布尔值等都以JSON格式输出,避免因类型差异导致的格式混乱。

实现默认返回text/plain的方案

如果希望基本类型默认返回text/plain,可以自定义HttpMessageConverter并调整优先级:

1. 自定义HttpMessageConverter

@Component
public class PrimitiveHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    public PrimitiveHttpMessageConverter() {
        super(MediaType.TEXT_PLAIN);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return clazz.isPrimitive() || 
               clazz.isAssignableFrom(Boolean.class) || 
               clazz.isAssignableFrom(Integer.class) || 
               clazz.isAssignableFrom(Long.class) || 
               clazz.isAssignableFrom(Double.class);
    }

    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException {
        throw new UnsupportedOperationException("Request handling not supported");
    }

    @Override
    protected void writeInternal(Object value, HttpOutputMessage outputMessage) throws IOException {
        outputMessage.getBody().write(value.toString().getBytes(StandardCharsets.UTF_8));
    }
}

2. 调整转换器优先级

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private PrimitiveHttpMessageConverter primitiveHttpMessageConverter;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 将自定义转换器放在首位,确保优先处理基本类型
        converters.add(0, primitiveHttpMessageConverter);
    }
}

内容的提问来源于stack exchange,提问作者WonChul Heo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:10:28