gson反序列化long型時間戳問題解決記錄


問題:接口返回的時間格式是long型的時間戳,使用GSON.fromJson(json, typeOfT)解析失敗
原因: GSON無法直接解析long類型的時間戳,需要自定義和注冊適配器

image
image

點擊查看代碼
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系列


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM