1. 程式人生 > >(二)初識springboot之使用fastjson解析資料(解決亂碼及簡單配置)

(二)初識springboot之使用fastjson解析資料(解決亂碼及簡單配置)

寫在前面的

在我們的專案的開發中,根據不同的需求有時候需要從後臺返回json資料。在Spring中常用的返回json資料的兩種方法是:(1)使用@RestController在控制器的類上註解,使用該註解的類中所有配置的url對映的方法返回值不進行檢視解析,只進行資料解析。(2)使用@Controller在控制器類上註解,在方法上使用@ResponseBody註解,使用該方法的只有在帶有@ResponseBody註解的配置url對映的方法返回值不進行檢視解析。

在springboot中如果不自定義json解析工具,預設使用的是jackson,但在我們日常開發中fastjson使用的比較多,所以本次是介紹如何自定義json解析器

一、在自己的工程中新增fastjson依賴

在pom.xml新增如下依賴

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

二、編寫程式碼,自定義json解析器

使用更換json解析器有兩種方法:

(1)啟動類繼承WebMvcConfigurerAdapter重寫configureMessageConverters方法

完整程式碼如下:

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {
    public static void main(String[] args){
        SpringApplication.run(Application.class,args);
    }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
        super
.configureMessageConverters(converters); //定義訊息轉換器 FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //設定配置資訊 FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //將配置資訊新增到轉換器中 fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); //將自定義的轉換器新增到轉換器列表中 converters.add(fastJsonHttpMessageConverter); } }
(1)使用@Bean注入訊息轉換器

完整程式碼如下:

 @Bean
    public HttpMessageConverters fastJsonHttpMessageConverter()
    {
        //定義訊息轉換器
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //設定配置資訊
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //將配置資訊新增到轉換器中
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        //將自定義的轉換器新增到轉換器列表中
        return new HttpMessageConverters(fastJsonHttpMessageConverter);
    }

使用加入以上程式碼後程序就會使用fastjson返回的資料

三、解決中文亂碼

使用fastjson解析是出現中文亂碼有兩種解決方式

(1)在轉換器中設定字符集
List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);

你可以點開MediaType中原始碼看到,其實就是設定了字符集

//第37行
public static final MediaType APPLICATION_JSON_UTF8 = valueOf("application/json;charset=UTF-8");
(2)設定response的字符集

在配置檔案中加入:

spring:
  http:
    encoding:
      charset: UTF-8
      enabled: true
#     force是將request和response都設定字符集
      force: true
#     force單獨設定request和response
#     force-response: true
#     force-request: false

本人使用的是yml的配置所以多行的,一般專案中建議兩個地方都設定統一字符集,比較安全保險

有的朋友提出要設定:
fastJsonConfig.setCharset(Charset.forName(“UTF-8”));
其實這一句可以不用,你檢視原始碼發現,他預設的配置就是UTF-8,所以可以不寫的。

四、資料格式簡單配置

1、資料解析樣式配置可以設定

fastJsonConfig.setSerializerFeatures(
    SerializerFeature.PrettyFormat,//結果是否格式化預設false
    SerializerFeature.WriteClassName,//輸出類名字預設false
);

如果你需要更多格式可以檢視列舉類SerializerFeature中的定義

2、另外還可以使用ValueFilter進行資料過濾,例如日期過濾

ValueFilter valueFilter = new ValueFilter() {
    public Object process(Object o, String key, Object value) {
        if(null!=value){
            if(value instanceof Date){
                value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(value);
            }
        }
        return value;
    }
};
fastJsonConfig.setSerializeFilters(valueFilter);

更多需求都可以自己設計自定義。

當然使用註解@JSONField(format = “yyyy-MM-dd”)也可定義日期格式,但是使用註解只有註解的屬性生效,對於太多相同設定使用這種方式更加便捷