[Spring Boot] 抛弃JacksonBind, 使用Gson作为HttpMessageConverter

网上查了一大堆, 都写得跟个啥似的… 用Gson作为HttpMessageConverter很简单啊

application.yml中添加:

spring:
  http:
    converters:
      preferred-json-mapper: gson

或者application.properties:

spring.http.converters.preferred-json-mapper=gson

这就搞定了.

但是, 还没完, 改完这个会出现:

Gson和Swagger不兼容问题

简单, 加个类就可以啦!


import com.google.gson.*
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.http.HttpMessageConverters
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.json.GsonHttpMessageConverter
import springfox.documentation.spring.web.json.Json
import java.lang.reflect.Type

/**
 * GsonConfig类, 用于解决默认配置与Swagger不兼容问题
 * @author HarrisonQI
 */
@Configuration
class GsonConfig {
    private val GSON_DATE_FORMAT: String = "yyyy-MM-dd HH:mm:ss"
    @Bean
    fun gson(): Gson {
        return GsonBuilder().setDateFormat(GSON_DATE_FORMAT).registerTypeAdapter(Json::class.java, SpringFoxJsonToGsonAdapter()).create()
    }

    @Bean
    fun httpMessageConverters(): HttpMessageConverters {
        val gsonHttpMessageConverter = GsonHttpMessageConverter()
        gsonHttpMessageConverter.gson = gson()
        return HttpMessageConverters(true, listOf(gsonHttpMessageConverter))
    }

}

internal class SpringFoxJsonToGsonAdapter : JsonSerializer<Json> {
    override fun serialize(json: Json, type: Type, context: JsonSerializationContext): JsonElement = JsonParser().parse(json.value())
}

你可能感兴趣的:(Springboot,Gson)