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

如何在Gson的TypeAdapter处理Instant类型时跳过JSON中的null值

解决Gson序列化Instant时跳过null字段的问题

要实现序列化时跳过null的Instant字段,无需写入特殊值,只需修改TypeAdapter的write方法,并调整read方法处理空值场景,代码如下:

gsonBuilder.registerTypeAdapter(Instant.class, new TypeAdapter<Instant>(){
    @Override
    public void write(final JsonWriter jsonWriter, final Instant instant) throws IOException {
        if (instant != null) {
            jsonWriter.value(instant.toEpochMilli());
        } else {
            // 跳过该字段,不在JSON中生成键值对
            jsonWriter.skipValue();
        }
    }

    @Override
    public Instant read(final JsonReader jsonReader) throws IOException {
        // 处理JSON中字段显式为null的情况
        if (jsonReader.peek() == JsonToken.NULL) {
            jsonReader.nextNull();
            return null;
        }
        long millisEpoch = jsonReader.nextLong();
        return Instant.ofEpochMilli(millisEpoch);
    }
});

关键说明

  • 序列化阶段:调用jsonWriter.skipValue()会让Gson直接跳过当前字段的输出,不会在最终JSON文本中保留该键值对,完全符合避免写入特殊值的需求。
  • 反序列化阶段:增加JsonToken.NULL的判断,避免当JSON中该字段显式为null时,直接调用nextLong()抛出异常;若JSON中不存在该字段,Gson会自动将对应Java对象的Instant字段赋值为null,无需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:22:13