Gson toJson 忽略 long 为 0的数据
起因于数据id过大,所以将对应int , Integer都修改为long,
测试过程中发现 Gson toJson时,字段将int为0的数据忽略,但long 没有,
所以
1. 新增适配器
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)
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
new Gson().toJson(new XXXBean(xxx,xxx,xxx))
03/09
更新一下,应该为longValue,之前写错为intValue了
longValue

浙公网安备 33010602011771号