diff --git a/pom.xml b/pom.xml index 5f3789f..72e27f2 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.spring4all swagger-spring-boot-starter - 1.9.0.RELEASE + 1.9.1.RELEASE spring-boot-starter-swagger https://github.com/SpringForAll/spring-boot-starter-swagger @@ -90,6 +90,12 @@ ${version.lombok} provided + + com.google.code.gson + gson + true + provided + diff --git a/src/main/java/com/spring4all/swagger/EnableSwagger2Doc.java b/src/main/java/com/spring4all/swagger/EnableSwagger2Doc.java index 411174d..ff91b68 100644 --- a/src/main/java/com/spring4all/swagger/EnableSwagger2Doc.java +++ b/src/main/java/com/spring4all/swagger/EnableSwagger2Doc.java @@ -13,7 +13,10 @@ @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited -@Import({SwaggerAutoConfiguration.class}) +@Import({ + SwaggerAutoConfiguration.class, + GsonSerializerConfigration.class +}) public @interface EnableSwagger2Doc { diff --git a/src/main/java/com/spring4all/swagger/GsonSerializerConfigration.java b/src/main/java/com/spring4all/swagger/GsonSerializerConfigration.java new file mode 100644 index 0000000..367799b --- /dev/null +++ b/src/main/java/com/spring4all/swagger/GsonSerializerConfigration.java @@ -0,0 +1,39 @@ +package com.spring4all.swagger; + +import com.google.gson.*; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +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; + +/** + * @Author: He Zhigang + * @Date: 2019/5/8 10:48 + * @Description: + */ +@Slf4j +@Configuration +@ConditionalOnProperty(name = "spring.http.converters.preferred-json-mapper", havingValue = "gson") +public class GsonSerializerConfigration { + class SpringfoxJsonToGsonSerializer implements JsonSerializer { + @Override + public JsonElement serialize(Json json, Type type, JsonSerializationContext jsonSerializationContext) { + final JsonParser parser = new JsonParser(); + return parser.parse(json.value()); + } + } + + @Bean + public GsonHttpMessageConverter gsonHttpMessageConverter() { + GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter(); + final GsonBuilder builder = new GsonBuilder(); + builder.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonSerializer()); + log.info("注册 SpringfoxJsonToGsonSerializer TypeAdapter"); + gsonHttpMessageConverter.setGson(builder.create()); + return gsonHttpMessageConverter; + } +}