如何在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
相关产品推荐
相关产品推荐

