简体   繁体   中英

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?

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 objects and primitives and it boxes primitives to wrappers in the filter.equals() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM