Gson Converter with SimpleDateFormat
I am running a code that uses a Gson Converter with a simple date format function and from time to time the date formatting gets confused with either displaying the date in 1969-1970 depending on the timezone, or taking it and displaying some random date.
static class DateSerializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context)
throws JsonParseException {
for (SimpleDateFormat simpleDateFormat : DATE_FORMATS) {
try {
simpleDateFormat.setLenient(true);
return simpleDateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
}
}
return null;
}
}
static {
final TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
int i = 0;
for (String format : DATE_FORMAT_STRINGS) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.US);
dateFormat.setTimeZone(GMT_TIMEZONE);
DATE_FORMATS[i++] = dateFormat;
}
}
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateSerializer())
.create();
private static final String[] DATE_FORMAT_STRINGS = new String[]{"yyyy-MM-dd'T'HH:mm:ssZZZZ",
"yyyy-MM-dd'T'HH:mm:ss'Z'"};
source to share
The problem is that SimpleDateFormat
it is not thread safe . Your deserialization happens on multiple threads to improve performance, but due to threadless safety, SimpleDateFormat
you sometimes get garbage back on your parsed dates.
Two options for solving this problem are to create a new SimpleDateFormat
one every time you need it, or to provide atomicity by doing something like creating a lock on your date format.
For example, GSON DefaultDateTypeAdapter
takes the latter approach.
source to share