今天在把对象转为 json 时需要去除 key 或者 value 为 null 或空字符串的属性,特此记录一下后续好复用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static String toJSONString(Object object) {
SerializerFeature[] serializerFeatures = new SerializerFeature[] {
//格式化时间
SerializerFeature.WriteDateUseDateFormat
};
return JSON.toJSONString(object, new ValueFilter() {
@Override
public Object process(Object object, String name, Object value) {
               // 如果名称或者值为null或空字符串,则不序列化该属性
if (name == null || (name instanceof String && ((String) name).isEmpty()) ||
value == null || (value instanceof String && ((String) value).isEmpty())) {
return null;
}
return value;
}
}, serializerFeatures);
}

更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Hito Li 微信支付

微信支付

Hito Li 支付宝

支付宝