今天在把对象转为 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) { if (name == null || (name instanceof String && ((String) name).isEmpty()) || value == null || (value instanceof String && ((String) value).isEmpty())) { return null; } return value; } }, serializerFeatures); }
|