我正在运行一个代码,该代码使用具有简单日期格式功能的 Gson 转换器,有时日期格式会困惑,要么根据时区显示 1969-1970 年的日期,要么采用它并随机显示日期。
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'"};
最佳答案
问题是 SimpleDateFormat
is not thread-safe .您的反序列化发生在多个线程中以提高性能,但由于 SimpleDateFormat
的非线程安全性,您偶尔会在解析的日期中返回垃圾。
解决此问题的两个选项是在每次需要时创建一个新的 SimpleDateFormat
,或者通过对日期格式创建锁定来强制执行原子性。
例如GSON的DefaultDateTypeAdapter
采用后一种方法。
关于带有 SimpleDateFormat 的 Gson 转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31342698/