spring boot 接收JSON时发生转义字符绑定对象失败

本文介绍了解决SpringBoot项目中JSON转义字符绑定对象失败的问题。通过引入fastjson依赖并配置FastJsonHttpMessageConverter来处理包含特殊字符的JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做Spring boot 项目时发生json转义字符绑定对象失败,原因是json里面有些字段包括空格,反斜杠等,如果框架没有对这些json进行转化时,就会报类似如下错误
org.codehaus.jackson.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 9)): has to be escaped using backslash to be included in string value
at [Source: java.io.StringReader@10cfc2e3; line: 1, column: 2461]

解决办法:
1.pom.xml文件增加fastjson依赖

 <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.2.15</version>
 </dependency>

2.增加配置类


import java.util.List;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;


@SpringBootApplication
public class JsonController extends WebMvcConfigurerAdapter {

      @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            super.configureMessageConverters(converters);

            FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

            FastJsonConfig fastJsonConfig = new FastJsonConfig();
            fastJsonConfig.setSerializerFeatures(
                    SerializerFeature.PrettyFormat
            );
            fastConverter.setFastJsonConfig(fastJsonConfig);

            converters.add(fastConverter);
        }

}

两步就可以了。。。。。。。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值