Skip to content

Commit

Permalink
support java.time.Instant serialization with gson
Browse files Browse the repository at this point in the history
  • Loading branch information
nobodyiam committed Dec 14, 2024
1 parent 95ca1ed commit 52df66e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -37,9 +42,23 @@
public class HttpMessageConverterConfiguration {
@Bean
public HttpMessageConverters messageConverters() {
// Custom Gson TypeAdapter for Instant
JsonSerializer<Instant> instantJsonSerializer = (src, typeOfSrc, context) ->
src == null ? JsonNull.INSTANCE : new JsonPrimitive(src.toString()); // Serialize Instant as ISO-8601 string

JsonDeserializer<Instant> 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<HttpMessageConverter<?>> converters = Lists.newArrayList(
new ByteArrayHttpMessageConverter(), new StringHttpMessageConverter(),
new AllEncompassingFormHttpMessageConverter(), gsonHttpMessageConverter);
Expand Down

0 comments on commit 52df66e

Please sign in to comment.