SpringBoot2使用Gson替代jackson並適配Swagger

SpringBoot2使用Gson替代jackson並適配Swagger

涉及到的軟件版本

  • SpringBoot:2.2.5.RELEASE
  • gson:2.8.6
  • springfox-swagger2:2.9.2

爲什麼使用Gson

Gson與fastJson、jackson相比,對泛型的支持比fastJson、jackson都要好。對於並不特別複雜的小型簡單數據結構的轉換處理,性能上有明顯優勢。所以棄用SpringBoot2中內置的jackson,用Gson替代。

如何使用Gson

spring-boot-starter-web中已經引了Gson的依賴,所以pom.xml中無需改動。

思路

1、創建一個GsonHttpMessageConverter,通過setDateFormat("yyyy-MM-dd")指定日期格式,通過registerTypeAdapter(Json.class, new GsonConfig())指定特殊類型的轉換規則(用於解決springfox不支持Gson的問題)。
2、再將GsonHttpMessageConverter放入HttpMessageConverters中。
3、在SpringApplication啓動類中禁止JacksonAutoConfiguration

完整代碼示例

Gson配置類
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import springfox.documentation.spring.web.json.Json;
/**
 * SpringfoxJsonToGsonAdapter
 */
@Configuration
public class GsonConfig implements JsonSerializer<Json> {
    
    @Bean
    public HttpMessageConverters customConverters() {

        Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
        gsonHttpMessageConverter.setGson(
        		new GsonBuilder()
        			.setDateFormat("yyyy-MM-dd")
        			.registerTypeAdapter(Json.class, new GsonConfig())
        			.create());
        messageConverters.add(gsonHttpMessageConverter);

        return new HttpMessageConverters(true, messageConverters);
    }

	@SuppressWarnings("deprecation")
	@Override
	public JsonElement serialize(Json json, Type type, JsonSerializationContext context) {
		final JsonParser parser = new JsonParser();
        return parser.parse(json.value());
	}
}
SpringApplication啓動類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;

/**
 * SpringApplication
 */
...
@SpringBootApplication(exclude = { JacksonAutoConfiguration.class })
public class MyBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyBootApplication.class, args);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章