Android 开发,Gson 解析 JSON 数据,时间戳转换为 Date 类型时的问题:com.google.gson.JsonSyntaxException: 1753945106316

张开发
2026/4/21 0:14:49 15 分钟阅读

分享文章

Android 开发,Gson 解析 JSON 数据,时间戳转换为 Date 类型时的问题:com.google.gson.JsonSyntaxException: 1753945106316
在 Android 中使用 Gson 解析 JSON 数据将时间戳转换为 Date 类型时出现如下错误信息com.google.gson.JsonSyntaxException: 1753945106316问题复现DataAllArgsConstructorNoArgsConstructorpublicclassShopRecord{privateIntegerid;privateStringname;privateDoubleprice;privateDatetime;}StringjsonStr{\id\:1,\name\:\apple\,\price\:10.0,\time\:1753945106316};GsongsonnewGson();ShopRecordshopRecordgson.fromJson(jsonStr,ShopRecord.class);System.out.println(shopRecord);# 输出结果 com.google.gson.JsonSyntaxException: 1753945106316问题原因Gson 默认无法直接将数字时间戳自动转换为 Date 类型需要自定义解析逻辑处理策略注册一个自定义的 JsonDeserializer将时间戳转换为 Date 类型StringjsonStr{\id\:1,\name\:\apple\,\price\:10.0,\time\:1753945106316};GsongsonnewGsonBuilder().registerTypeAdapter(Date.class,newJsonDeserializerDate(){OverridepublicDatedeserialize(JsonElementjson,TypetypeOfT,JsonDeserializationContextcontext)throwsJsonParseException{// 如果 JSON 是数字时间戳转换为 Dateif(json.isJsonPrimitive()json.getAsJsonPrimitive().isNumber()){returnnewDate(json.getAsLong());}// 其他情况例如ISO 8601 字符串交给默认解析器returnnewGson().fromJson(json,Date.class);}}).create();ShopRecordshopRecordgson.fromJson(jsonStr,ShopRecord.class);System.out.println(shopRecord);# 输出结果 ShopRecord(id1, nameapple, price10.0, timeThu Jul 31 14:58:26 CST 2025)修改字段类型为 Long 类型DataAllArgsConstructorNoArgsConstructorpublicclassShopRecord{privateIntegerid;privateStringname;privateDoubleprice;privateLongtime;}StringjsonStr{\id\:1,\name\:\apple\,\price\:10.0,\time\:1753945106316};GsongsonnewGson();ShopRecordshopRecordgson.fromJson(jsonStr,ShopRecord.class);System.out.println(shopRecord);# 输出结果 ShopRecord(id1, nameapple, price10.0, time1753945106316)使用 ISO 8601 字符串格式Gson 默认支持该格式StringjsonStr{\id\:1,\name\:\apple\,\price\:10.0,\time\:\Jul 31, 2025, 4:12:43 PM\};GsongsonnewGson();ShopRecordshopRecordgson.fromJson(jsonStr,ShopRecord.class);System.out.println(shopRecord);# 输出结果 ShopRecord(id1, nameapple, price10.0, timeThu Jul 31 16:12:43 CST 2025)

更多文章