You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android(Java)中Gson无法序列化LocalDateTime的问题排查

Android中Gson序列化LocalDateTime的问题

[更新于2023年2月20日] 此前示例中混淆了LocalDateTime与Instant类型,现已修正,带来不便敬请谅解,谢谢

我在Android Java开发练习中遇到Gson序列化LocalDateTime的问题。例如,我创建了如下Java对象:

public class Person {
private String name;
private LocalDateTime createdAt;

// 构造方法
// Getter和Setter方法
}

随后我使用Gson将该Person对象转换为JSON:

Person person = new Person("John Doe", LocalDateTime.now()); //示例时间:2022-02-02T11:11:04.5701100
String personJsonAsString = new Gson().toJson(person);

我期望得到的JSON为:

{
"name": "John Doe",
"createdAt": "2022-02-02T11:11:04.5701100"
}

但实际结果是:

{
"name": "John Doe",
"createdAt": {} // <- 此处为空对象
}

之后我查阅资料得知可通过GsonBuilder注册自定义序列化类,于是尝试如下代码:

Person person = new Person("John Doe", LocalDateTime.now()); //示例时间:2022-02-02T11:11:51.0Z
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeJsonSerializer()).create();
String personJsonAsString = gson.toJson(person);

其中LocalDateTimeJsonSerializer为我编写的类:

public class LocalDateTimeJsonSerializer implements JsonSerializer<LocalDateTime> {
    @Override
    public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
    }
}

当我在Android应用中尝试持久化数据时抛出了异常,异常信息如下:

java.lang.NoClassDefFoundError: Failed resolution of: Ljava/time/format/DateTimeFormatter;

目前我无法确定Android平台上Gson无法序列化LocalDateTime的原因,恳请帮助。非常感谢您的时间。

已尝试的操作:

  • 在StackOverflow上查阅相关问题
  • 尝试各种可用解决方案

期望:
了解该异常的根本原因,而非仅修复问题使其运行。


内容的提问来源于stack exchange,提问作者Trần Vô Bảo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:30:44