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

Spring应用Rest API接收含 的JSON时Jackson解析报错求助

解决Jackson解析含未转义制表符JSON的异常

你遇到的问题是Jackson默认不允许字符串中包含未转义的控制字符(比如制表符\t,对应ASCII码9),而你发送的JSON数据里恰好包含这类未转义字符,导致解析失败。以下是几种可行的解决方式:

1. Spring Boot 全局配置

直接在配置文件中开启允许未转义控制字符的选项:

  • 若使用application.properties:
spring.jackson.parser.allow-unquoted-control-chars=true
  • 若使用application.yml:
spring:
  jackson:
    parser:
      allow-unquoted-control-chars: true

2. 自定义ObjectMapper(适用于所有Spring项目)

通过配置类自定义Jackson的核心解析器,全局生效:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 允许字符串中存在未转义的控制字符
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        return mapper;
    }
}

3. 单个接口专属配置

如果不需要全局生效,仅针对特定接口处理,可以手动使用自定义ObjectMapper解析请求体:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class IncomeController {

    private final ObjectMapper customMapper;

    public IncomeController() {
        customMapper = new ObjectMapper();
        customMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    }

    @PostMapping("/api/income")
    public String handleIncome(@RequestBody String rawBody) throws IOException {
        // 手动解析请求体为DTO
        IncomeDto dto = customMapper.readValue(rawBody, IncomeDto.class);
        return "Received value: " + dto.getIncomeValue();
    }

    // 定义对应的DTO类
    static class IncomeDto {
        private String incomeValue;

        public String getIncomeValue() {
            return incomeValue;
        }

        public void setIncomeValue(String incomeValue) {
            this.incomeValue = incomeValue;
        }
    }
}

开启上述配置后,Jackson就能正常解析包含未转义制表符的JSON数据,不会再抛出JsonParseException异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:05:05