gson反序列化long型时间戳问题解决记录
问题:接口返回的时间格式是long型的时间戳,使用GSON.fromJson(json, typeOfT)解析失败
原因: GSON无法直接解析long类型的时间戳,需要自定义和注册适配器
点击查看代码
GsonBuilder builder = new GsonBuilder();
// Register an adapter to manage the date types as long values
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = builder.create();
gson.fromJson(json, clazz);
参考链接:
【1】解决Gson解析日期报错的问题 - 简书
【2】[android - "Unparseable date: 1302828677828" trying to deserialize with Gson a millisecond-format date received from server - Stack Overflow](https://stackoverflow.com/questions/5671373/unparseable-date-1302828677828-trying-to-deserialize-with-gson-a-millisecond "android - "Unparseable date: 1302828677828" trying to deserialize with Gson a millisecond-format date received from server - Stack Overflow")
【3】关于Gson解析时间时的问题 - SegmentFault 思否
【4】https://sites.google.com/site/gson/gson-user-guide
【5】https://github.com/google/gson/blob/master/UserGuide.md
【6】https://blog.csdn.net/sunrainamazing/article/details/80989711
【7】Gson User Guide
【8】你真的会用Gson吗?Gson使用指南
【9】Gson系列