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

如何使用Gson将不同Java DateTime对象序列化为字符串?

解决Gson序列化Java 8日期时间对象为字符串的问题

你遇到的核心问题是:Gson默认仅支持旧版java.util.Date类的格式化,而你使用的OffsetDateTime属于Java 8引入的java.time时间API,setDateFormat方法对这类新时间类完全无效,这就是之前所有配置都不起作用的原因。

以下是两种可行的解决方案:

方案1:使用官方Gson Java 8扩展库(最省心)

Google官方提供了专门适配Java 8时间API的扩展模块,只需引入依赖并注册模块即可:

  1. 添加依赖
    Maven:

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson-java8</artifactId>
        <version>2.10.1</version> <!-- 建议使用最新稳定版 -->
    </dependency>
    

    Gradle:

    implementation 'com.google.code.gson:gson-java8:2.10.1'
    
  2. 修改Gson初始化代码

    Gson gson = new GsonBuilder()
            .serializeNulls()
            .registerModule(new JavaTimeModule()) // 关键:注册Java 8时间适配模块
            .create();
    
    String json = gson.toJson(myObject);
    

    此方案会自动将OffsetDateTime、LocalDateTime等java.time类序列化为标准ISO 8601格式的字符串,与你原始JSON的格式完全匹配。

方案2:自定义TypeAdapter(无需额外依赖)

如果不想引入新依赖,可以手动编写序列化/反序列化适配器:

  1. 编写OffsetDateTime适配器

    import com.google.gson.TypeAdapter;
    import com.google.gson.stream.JsonReader;
    import com.google.gson.stream.JsonWriter;
    import java.io.IOException;
    import java.time.OffsetDateTime;
    import java.time.format.DateTimeFormatter;
    
    public class OffsetDateTimeAdapter extends TypeAdapter<OffsetDateTime> {
        // 匹配你原始JSON的日期格式
        private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
    
        @Override
        public void write(JsonWriter out, OffsetDateTime value) throws IOException {
            if (value == null) {
                out.nullValue();
                return;
            }
            out.value(FORMATTER.format(value));
        }
    
        @Override
        public OffsetDateTime read(JsonReader in) throws IOException {
            String dateStr = in.nextString();
            return OffsetDateTime.parse(dateStr, FORMATTER);
        }
    }
    
  2. 注册适配器到Gson

    Gson gson = new GsonBuilder()
            .serializeNulls()
            .registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeAdapter())
            .create();
    
    String json = gson.toJson(myObject);
    

    这种方式支持完全自定义日期格式,只需修改DateTimeFormatter即可适配非标准格式。

效果验证

使用上述任一方案后,序列化后的date字段会恢复为预期的字符串形式:

"date": "2000-04-26T10:10:00Z"

内容的提问来源于stack exchange,提问作者jumps4fun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:45:33