今天在把对象转为 json 时需要去除 key 或者 value 为 null 或空字符串的属性,特此记录一下后续好复用。
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); | |
} |