GSON default date serializer is locale-specific
See original GitHub issueThis has caused problems for Caliper, which was relying on the default date
serializer:
http://code.google.com/p/caliper/issues/detail?id=113
Work-around the problem by registering a date type adapter like the following:
private static class DateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private final DateFormat dateFormat;
private DateTypeAdapter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
@Override public synchronized JsonElement serialize(Date date, Type type,
JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
@Override public synchronized Date deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
Original issue reported on code.google.com by limpbizkit
on 30 Jan 2011 at 1:01
Issue Analytics
- State:
- Created 9 years ago
- Comments:15
Top Results From Across the Web
GSON default date serializer is locale-specific - Stack Overflow
The problem is that the server is returning the date as "Nov 1, 2019". In this format you don't have the time and...
Read more >Gson (Gson 2.2.4 API) - javadoc.io
Gson provides default serialization and deserialization for Enums, Map , URL , URI , Locale , Date , BigDecimal , and BigInteger classes....
Read more >com.google.gson.GsonBuilder.setDateFormat java code ...
Configures Gson to to serialize Date objects according to the style value provided. You can call this method or #setDateFormat(String) multiple times, but...
Read more >How to format a date using the Gson library in Java?
A Gson is a JSON library for Java, which is created by Google. ... setDateFormat() method configures Gson to serialize Date objects ...
Read more >Deserialize and Serialize DateTime with GSON | by Hao
And we want to serialize it into a format, like “yyyy-MM-dd”. Response contains two different types of Date format. GsonBuilder's setDateFormat.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
In case anyone was wondering where
UtcDateTypeAdapter.java
ended up, it’s part ofgson-extras
:https://github.com/google/gson/blob/d9cc7bc60b492664fe9f328d1bab9f9ae873f4d4/extras/src/main/java/com/google/gson/typeadapters/UtcDateTypeAdapter.java
Worked as: