Gson toJson 忽略 long 为 0的数据
起因于数据id过大,所以将对应int , Integer都修改为long,
测试过程中发现 Gson toJson时,字段将int为0的数据忽略,但long 没有,
所以
1. 新增适配器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; public class LongIgnoreZeroAdapter extends TypeAdapter<Long> { @Override public void write(JsonWriter jsonWriter, Long aLong) throws IOException { if (aLong == null || aLong.equals(0l)) { jsonWriter.nullValue(); return ; } jsonWriter.value(aLong.longValue()); } @Override public Long read(JsonReader jsonReader) throws IOException { if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); return 0l; } return jsonReader.nextLong(); } } |
2. 在对应类中字段上方新增注解 @JsonAdapter(LongIgnoreZeroAdapter.class)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import com.xxx.xxxx.adapter.LongIgnoreZeroAdapter; import com.google.gson.annotations.JsonAdapter; public class XXXBean { @JsonAdapter (LongIgnoreZeroAdapter. class ) private long xx1; private String xx2; public XXXBean( long xx1, String xx2) { this .xx1 = xx1; this .xx2 = xx2; } } |
3. 正常toJson
1 | new Gson().toJson( new XXXBean(xxx,xxx,xxx)) |
03/09
更新一下,应该为longValue,之前写错为intValue了
longValue
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
2022-02-07 Html Websocket
2022-02-07 非常简易的SpringBoot后台项目
2022-02-07 Class<T> clazz 传参