问题
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?
回答1:
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
filterObject (specified byJsonInclude.valueFilter()for value itself, and/orJsonInclude.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.
来源:https://stackoverflow.com/questions/56493606/jackson-serialization-ignore-negative-values