Android中保存LocalDateTime到JSON为空的问题求助
解决Gson序列化LocalDateTime为空对象的问题
Gson默认不支持Java 8引入的java.time包下的日期时间类(比如LocalDateTime、LocalDate),直接序列化这些类型的对象时,Gson无法识别其内部结构,所以会输出空对象{}。以下是两种可行的解决方案:
方案一:使用Gson的Java 8时间扩展库
这是最简便的官方适配方案:
- 在Module级别的
build.gradle中添加依赖:
implementation 'com.google.code.gson:gson:2.10.1' implementation 'com.google.code.gson:gson-java8:2.10.1'
- 修改Gson实例创建代码,注册Java时间模块:
public void WriteJsonToStorage(){ Gson gson = new GsonBuilder() .setPrettyPrinting() .registerModule(new JavaTimeModule()) // 注册Java 8时间适配模块 .create(); String json = gson.toJson(bookingToWrite); try (FileOutputStream fos = context.openFileOutput("SingleBooking.txt", Context.MODE_PRIVATE)) { fos.write(json.getBytes()); } catch (IOException e) { e.printStackTrace(); } }
方案二:自定义TypeAdapter
如果不想引入额外依赖,可以手动实现序列化逻辑:
- 编写
LocalDateTime的自定义适配器:
public class LocalDateTimeTypeAdapter extends TypeAdapter<LocalDateTime> { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME; @Override public void write(JsonWriter out, LocalDateTime value) throws IOException { if (value == null) { out.nullValue(); return; } out.value(FORMATTER.format(value)); } @Override public LocalDateTime read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } String dateStr = in.nextString(); return LocalDateTime.parse(dateStr, FORMATTER); } }
- 在创建Gson实例时注册该适配器:
public void WriteJsonToStorage(){ Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeTypeAdapter()) // 注册自定义适配器 .create(); String json = gson.toJson(bookingToWrite); try (FileOutputStream fos = context.openFileOutput("SingleBooking.txt", Context.MODE_PRIVATE)) { fos.write(json.getBytes()); } catch (IOException e) { e.printStackTrace(); } }
额外检查点
- 确认
bookingToWrite对象的bookingDateTime字段已被正确赋值为有效LocalDateTime实例; - 时间输入框的字符串格式要符合
LocalTime.parse()的默认规则(如HH:mm或HH:mm:ss),若使用自定义格式,需在解析时指定对应DateTimeFormatter。
内容的提问来源于stack exchange,提问作者ThebulletKin
相关产品推荐
相关产品推荐

