javajsonjacksonfasterxml

Jackson Json Serialization : Remove Blank strings


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 ?


Solution

  • 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)
    

    and here is the custom filter -

    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;
        }
    }
    

    As per the javadoc of CUSTOM filter -

    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.