Jackson Json 序列化:删除空白字符串
Jackson Json Serialization : Remove Blank strings
我正在尝试使用 Jackson 从生成的 Json 中排除所有空白字符串。
我知道我可以使用下面的注释来过滤它,但这似乎不能处理空白字符串。[只有空格的字符串]
@JsonInclude(JsonInclude.Include.NON_EMPTY)
有办法吗?
您可以使用 custom value filter
,请试试这个,如果这对您有用,请告诉我 -
@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 -
public static final JsonInclude.Include CUSTOM
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 中排除所有空白字符串。
我知道我可以使用下面的注释来过滤它,但这似乎不能处理空白字符串。[只有空格的字符串]
@JsonInclude(JsonInclude.Include.NON_EMPTY)
有办法吗?
您可以使用 custom value filter
,请试试这个,如果这对您有用,请告诉我 -
@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 -
public static final JsonInclude.Include CUSTOM
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.