Jackson serialization ignore negative values

无人久伴 提交于 2020-01-14 19:23:48

问题


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 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.



来源:https://stackoverflow.com/questions/56493606/jackson-serialization-ignore-negative-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!