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 18c339d
Show file tree
Hide file tree
Showing 2 changed files with 15 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,9 @@
import com.google.common.collect.Lists;
import com.google.gson.GsonBuilder;

import com.google.gson.JsonDeserializer;
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 +40,19 @@
public class HttpMessageConverterConfiguration {
@Bean
public HttpMessageConverters messageConverters() {
// Custom Gson TypeAdapter for Instant
JsonSerializer<Instant> instantJsonSerializer = (src, typeOfSrc, context) ->
context.serialize(src.toString()); // Serialize Instant as ISO-8601 string

JsonDeserializer<Instant> instantJsonDeserializer = (json, typeOfT, context) ->
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 18c339d

Please sign in to comment.