Samuel Philipp
Samuel Philipp

Reputation: 11050

Jackson serialization ignore negative values

I have an Object like this:

public class MyObject {
    private String name;
    private int number;
    // ...
}

And I want to include the number only if the value is not negative (number >= 0).

While researching I found Jackson serialization: ignore empty values (or null) and Jackson serialization: Ignore uninitialised int. Both are using the @JsonInclude annotation with either Include.NON_NULL, Include.NON_EMPTY or Include.NON_DEFAULT, but none of them fits my problem.

Can I somehow use @JsonInclude with my condition number >= 0 to include the value only if not negative? Or is there another solution how I can achieve that?

Upvotes: 3

Views: 2369

Answers (1)

davidxxx
davidxxx

Reputation: 131456

If you use Jackson 2.9+ version, you could try with a Include.Custom value for @JsonInclude.
From the JsonInclude.CUSTOM specification :

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.

That is a more specific and declarative approach than defining a custom serializer.

@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = PositiveIntegerFilter.class)
private int number;

// ...
public class PositiveIntegerFilter {
    @Override
    public boolean equals(Object other) {
       // Trick required to be compliant with the Jackson Custom attribute processing 
       if (other == null) {
          return true;
       }
       int value = (Integer)other;
       return value < 0;
    }
}

It works with objectsand primitives and it boxes primitives to wrappers in the filter.equals() method.

Upvotes: 4

Related Questions