document.write("");

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
posted @   人间春风意  阅读(66)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
历史上的今天:
2022-02-07 Html Websocket
2022-02-07 非常简易的SpringBoot后台项目
2022-02-07 Class<T> clazz 传参
点击右上角即可分享
微信分享提示

距今时间:
1018天1.00 小时 38.76 分钟

当前新增阅读数:139507