1. 程式人生 > >搭建 spring boot (二) ---- 配置fastjson,實體欄位格式化、欄位過濾、解決中文亂碼

搭建 spring boot (二) ---- 配置fastjson,實體欄位格式化、欄位過濾、解決中文亂碼

新增第一個實體並返回json到前端

1、新增第一個實體類Demo.java,設定簡單的屬性id和name並生成getter和setter方法

2、新增介面。在ctroller中新增返回demo的介面

3、重啟應用並訪問介面。可見返回的資料已經是json格式了。

疑問:為什麼我接口裡return一個物件,前端拿到的就是一個json呢?

答:因為Spring Boot會把返回的物件轉換成json,spring boot預設使用的json解析框架是jackson

4、使用fastjson代替預設的jackson。

    1)先引入依賴

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

    2)配置fastjson。在app.java中,加入如下程式碼。

     /**
     * 使用@Bean 注入fastJsonHttpMessageConvert
     * @return
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        // 1、需要先定義一個convert 轉換訊息的物件
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        
        // 2、新增fastJson 的配置資訊,比如:是否需要格式化返回的json資料
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig .setSerializerFeatures(SerializerFeature.PrettyFormat);
        
        // 處理中文亂碼
        List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMedisTypes);
        
        // 3、在convert中新增配置資訊
        fastConverter.setFastJsonConfig(fastJsonConfig);
        
        HttpMessageConverter<?> converter = fastConverter;
        return new HttpMessageConverters(converter);
    }

    3)測試。

    在實體類中新增一個時間欄位,並生成對應的getter和setter方法,再使用fastjson的註解進行格式化

    再呼叫相同的介面,如果返回的json中的時間欄位已經被格式化了,說明使用fastjson成功

5、過濾不想給前端看到的欄位。有時候我們不能把所有的欄位都返回給前端,這時候我們就需要欄位過濾。

使用fastjson的@JSONField(serialize= false)註解即可實現。(相比使用DTO,個人更喜歡這種方式,DTO還需要維護一套DTO bean,一旦庫表改了欄位,就同時改兩個bean)

---------------------------------edited @2018.07.28---------------------------

使用如上方式配置fastjson會導致controller返回的中文字串亂碼(json中的字串倒是沒有亂碼),如下圖

解決方法:

網上很多解決亂髮問題文章都說實現一個配置類繼承WebMvcConfigurerAdapter類,但我在用的時候發現SpringBoot2.0及Spring 5.0 的WebMvcConfigurerAdapter已經過時了。於是我另外找到WebMvcConfigurer介面

改變了配置fastjson的方式,新建一個WebAppConfig類實現WebMvcConfigurer介面,注入fastJson訊息轉換器,並替代預設的訊息轉換器。之前亂碼的原因是預設的訊息轉換器並不是UTF-8編碼的。有興趣的可以看下configureMessageConverters這個介面方法的預設實現,這裡不深入展開。

package com.jby.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

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

@Configuration
public class WebAppConfig implements WebMvcConfigurer{
	
	@Bean
	public HttpMessageConverter<Object> fastJsonHttpMessageConverter() {
		// 1.需要先定義一個convert 轉換訊息的物件
	    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
	    
	    // 2.新增fastJson的配置資訊,比如,是否需要格式化返回的json資料
	    FastJsonConfig fastJsonConfig = new FastJsonConfig();
	    
	    // 空值特別處理
	    // WriteNullListAsEmpty 將Collection型別欄位的欄位空值輸出為[]
	    // WriteNullStringAsEmpty 將字串型別欄位的空值輸出為空字串 ""
	    // WriteNullNumberAsZero 將數值型別欄位的空值輸出為0
	    // WriteNullBooleanAsFalse 將Boolean型別欄位的空值輸出為false
	    fastJsonConfig.setSerializerFeatures(
	    		SerializerFeature.PrettyFormat, 
	    		SerializerFeature.WriteNullListAsEmpty
	    		);
	    
	    // 處理中文亂碼問題
	    List<MediaType> fastMediaTypes = new ArrayList<>();
	    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
	    fastConverter.setSupportedMediaTypes(fastMediaTypes);
	    
	    // 3.在convert中新增配置資訊
	    fastConverter.setFastJsonConfig(fastJsonConfig);
	    return fastConverter;
	}
	
	// 配置訊息轉換器
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
	    converters.add(fastJsonHttpMessageConverter());
	}
	
	
}