diff --git a/CHANGES.md b/CHANGES.md index d278bf8a551..3591e1fd14f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -25,6 +25,7 @@ Apollo 2.4.0 * [Feature: Add rate limiting function to ConsumerToken](https://github.com/apolloconfig/apollo/pull/5267) * [Feature: add JSON formatting function in apollo-portal](https://github.com/apolloconfig/apollo/pull/5287) * [Fix: add missing url patterns for AdminServiceAuthenticationFilter](https://github.com/apolloconfig/apollo/pull/5291) +* [Fix: support java.time.Instant serialization with gson](https://github.com/apolloconfig/apollo/pull/5298) ------------------ All issues and pull requests are [here](https://github.com/apolloconfig/apollo/milestone/15?closed=1) diff --git a/apollo-common/src/main/java/com/ctrip/framework/apollo/common/controller/HttpMessageConverterConfiguration.java b/apollo-common/src/main/java/com/ctrip/framework/apollo/common/controller/HttpMessageConverterConfiguration.java index 87ef82e11bc..5b2b5136bda 100644 --- a/apollo-common/src/main/java/com/ctrip/framework/apollo/common/controller/HttpMessageConverterConfiguration.java +++ b/apollo-common/src/main/java/com/ctrip/framework/apollo/common/controller/HttpMessageConverterConfiguration.java @@ -19,6 +19,11 @@ import com.google.common.collect.Lists; import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonNull; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializer; +import java.time.Instant; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -37,9 +42,23 @@ public class HttpMessageConverterConfiguration { @Bean public HttpMessageConverters messageConverters() { + // Custom Gson TypeAdapter for Instant + JsonSerializer instantJsonSerializer = (src, typeOfSrc, context) -> + src == null ? JsonNull.INSTANCE : new JsonPrimitive(src.toString()); // Serialize Instant as ISO-8601 string + + JsonDeserializer instantJsonDeserializer = (json, typeOfT, context) -> { + if (json == null || json.isJsonNull()) { + return null; + } + return Instant.parse(json.getAsString()); // Deserialize from ISO-8601 string + }; + GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter(); gsonHttpMessageConverter.setGson( - new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create()); + new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .registerTypeAdapter(Instant.class, instantJsonSerializer) + .registerTypeAdapter(Instant.class, instantJsonDeserializer) + .create()); final List> converters = Lists.newArrayList( new ByteArrayHttpMessageConverter(), new StringHttpMessageConverter(), new AllEncompassingFormHttpMessageConverter(), gsonHttpMessageConverter);