spring boot 接收JSON時發生轉義字符綁定對象失敗

在做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);
        }

}

兩步就可以了。。。。。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章