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

Spring REST API返回字符串带双引号的差异原因及去引号方案

响应差异核心原因

  1. Spring Boot项目(ProjectA)默认自动装配时,会将StringHttpMessageConverter的优先级设置为高于Jackson系列的JSON消息转换器。当接口返回String类型时,会直接用该转换器将字符串以text/plain格式输出,不会触发JSON序列化,因此返回结果不带双引号。
  2. 普通Spring项目(ProjectB)默认消息转换器的排序中,MappingJackson2HttpMessageConverter优先级更高,当未明确指定响应Content-Type时,返回的String会被Jackson当做普通Java对象序列化为JSON字符串,因此会自动包裹双引号。
  3. 你添加的@Produces("text/plain")是JAX-RS规范的注解,Spring MVC默认不解析该注解,因此配置不生效,无法修改响应的Content-Type规则。

解决方案

方案1:全局调整消息转换器优先级

在Spring MVC配置类中显式注册StringHttpMessageConverter,并设置为更高优先级,所有String返回值的接口都会默认按纯文本输出:

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 优先注册String类型消息转换器,指定UTF-8编码避免中文乱码
        converters.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        // 后续再注册其他消息转换器(如JSON转换器)
    }
}

方案2:单个接口指定响应Content-Type

无需修改全局配置,仅需在对应接口的@PostMapping注解中添加Spring原生的produces参数,指定返回格式为纯文本:

@PostMapping(
    path = "/tenants/{tenantId}/script/getNormalString",
    produces = "text/plain;charset=UTF-8"
)
public String getNormalString(@PathVariable("tenantId") String tenantId,HttpServletRequest httpRequest) {
    // 原有业务逻辑不变
}

方案3:返回ResponseEntity手动指定响应头

最稳妥的单接口适配方案,无需依赖全局转换器排序,手动指定响应的Content-Type:

@PostMapping(path = "/tenants/{tenantId}/script/getNormalString")
public ResponseEntity<String> getNormalString(@PathVariable("tenantId") String tenantId,HttpServletRequest httpRequest) {
    try {
        String uuid = "normalString";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<>(uuid, headers, HttpStatus.OK);
    }  catch(Exception e) {
        logger.error("Error in getNormalString-> {}",e.getMessage(),e);
        throw new RestApiException(FAILED_GET,e.getMessage(),e);
    } 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:27:03