whitfin
whitfin

Reputation: 4629

Ignore given custom value Jackson JSON

If I have a property with a value set to "custom_string", is there a way to ignore it when using a POJO and Jackson?

I know you can ignore null using @JsonInclude(Include.NON_NULL), but is there a way to ignore a custom value? I can't seem to find any notes on this anywhere.

I know it's possible to just return value.equals("custom_string") ? null : value in my Getter... but I'd prefer a more elegant way.

Upvotes: 4

Views: 14342

Answers (3)

thomas77
thomas77

Reputation: 1150

Tried using JsonInclude.Include.Custom and it worked like a charm.

The annotation:

    @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = MaskingFilter.class)
    private String firstname;

The filter class:

    public class MaskingFilter {
      public MaskingFilter() {
      }

      @Override
      public boolean equals(Object value) {
        if(value == null)
            return true;
        return "****MASKED_VALUE****".equals(value);
      }
  }

if firstname in this case, equals "****MASKED_VALUE****" it is not a part of the result.

Upvotes: 5

vgalaguza
vgalaguza

Reputation: 91

One more possible solution is to use custom filter where you could combine more than one requirement. Let's say we want to filter null values and "custom_string", then we should specify that we will use JsonInclude.Include.CUSTOM value and provide filter implementation. Example:

@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = StringFilter.class)
private String name;

// Custom filter that will omit null and "custom_string" values.
public class StringFilter {
    @Override
    public boolean equals(Object other) {
        if (other == null) {
            // Filter null's.
            return true;
        }

        // Filter "custom_string".
        return "custom_string".equals(other);
    }
}

Upvotes: 9

yanana
yanana

Reputation: 2331

What is the smartest differs by your requirement.

Jackson provides the way to ignore the property with default value (by annotating class with @JsonSerialize(include = Inclusion.NON_DEFAULT), so if you could set the field's default value "custom_string", the solution might be available.

Other solutions I know are to convert the object to Map and then simply serialize, to add the annotation by reflection, or to create your own custom serializer. The custom serializer may look like this:

public class YourItem {
    public String key;
    public String item;
}

public class YourItemSerializer extends StdSerializer<YourItem> {
    @Override
    public void serialize(YourItem value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
        jgen.writeStartObject();
        jgen.writeStringField("key", value.key);
        if (!"custom_string".equals(value.item))
            jgen.writeStringField("item", value.item);
        jgen.writeEndObject();
    }
}

Upvotes: 1

Related Questions