Jackson Json序列化:删除空白字符串 [英] Jackson Json Serialization : Remove Blank strings
问题描述
我正在尝试使用杰克逊从生成的Json中排除所有空白字符串.
I am trying to exclude all Blank Strings from the resulting Json using Jackson.
我知道我可以使用下面的注释来对此进行过滤,但这似乎无法处理空白字符串.[仅带有空格的字符串]
I understand I can use below annotation to filter this, but this does not seem to handle Blank Strings.[Stings with just white spaces]
@JsonInclude(JsonInclude.Include.NON_EMPTY)
有没有办法做到这一点?
Is there a way to do this ?
推荐答案
您可以使用自定义值过滤器
,请尝试使用此方法,并让我知道它是否对您有用-
You can use custom value filter
, Please try this and let me know if this works for you -
@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = CustomFilter.class)
这是自定义过滤器-
class CustomFilter {
public CustomFilter() {
}
@Override
public boolean equals(Object obj) {
if(obj == null)
return true;
if(obj instanceof String){
return ((String)obj).trim().isEmpty();
}
return false;
}
}
根据CUSTOM过滤器的javadoc-
As per the javadoc of CUSTOM filter -
public static final JsonInclude.Include CUSTOM
该值指示单独的
filter
对象(由JsonInclude.valueFilter()用于值本身,和/或JsonInclude.contentFilter()用于结构化类型的内容)用于确定纳入标准.过滤对象的equals()用值调用方法进行序列化;如果返回true,则值为排除(即过滤掉);如果包含错误值.
Value that indicates that separate
filter
Object (specified by JsonInclude.valueFilter() for value itself, and/or JsonInclude.contentFilter() for contents of structured types) is to be used for determining inclusion criteria. Filter object's equals() method is called with value to serialize; if it returns true value is excluded (that is, filtered out); if false value is included.
这篇关于Jackson Json序列化:删除空白字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!