我已经将我的 Gson 实例构建为:
val DATE_FORMAT_MASK = "yyyy-MM-dd'T'HH:mm:ssZ"
val gson = GsonBuilder()
.setDateFormat(DATE_FORMAT_MASK)
.create()
在我执行一个空日期的序列化之前,这个工作正常
gson.toJson(null, Date::class.java)
然后我得到以下异常:
java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1770)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:943)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:936)
at java.text.DateFormat.format(DateFormat.java:345)
at com.google.gson.DefaultDateTypeAdapter.write(DefaultDateTypeAdapter.java:88)
at com.google.gson.DefaultDateTypeAdapter.write(DefaultDateTypeAdapter.java:40)
at com.google.gson.Gson.toJson(Gson.java:669)
at com.google.gson.Gson.toJson(Gson.java:648)
at com.google.gson.Gson.toJson(Gson.java:603)
我该如何处理这种情况?
可能是 Gson 库中的错误?
最佳答案
如果其他人遇到此问题,则该问题出现在 Gson 的 2.8.1 版中。回到 2.8.0 或前进到 2.8.2 解决了这个问题。如果你卡在 2.8.1 上,有 another workaround此错误报告中有详细说明:https://github.com/google/gson/issues/1096
private Gson getGson() {
// Trick to get the DefaultDateTypeAdatpter instance
// Create a first instance a Gson
Gson gson = new GsonBuilder()
.setDateFormat(DATE_FORMAT_COMPLETE)
.create();
// Get the date adapter
TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class);
// Ensure the DateTypeAdapter is null safe
TypeAdapter<Date> safeDateTypeAdapter = dateTypeAdapter.nullSafe();
// Build the definitive safe Gson instance
return new GsonBuilder()
.registerTypeAdapter(Date.class, safeDateTypeAdapter)
.create();
}
关于date - Gson setDateFormat 在日期为空时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46888187/