Jackson序列化忽略负值 [英] Jackson serialization ignore negative values
问题描述
我有一个像这样的对象:
I have an Object like this:
public class MyObject {
private String name;
private int number;
// ...
}
而且我只想在值不为负(number >= 0
)时包含number
.
And I want to include the number
only if the value is not negative (number >= 0
).
在进行研究时,我发现杰克逊序列化:忽略空值(或null)和
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.
我可以在条件number >= 0
中以某种方式使用@JsonInclude
来仅在不为负的情况下包括该值吗?还是有另一种解决方案我可以实现呢?
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?
推荐答案
如果使用Jackson 2.9+版本,则可以尝试使用Include.Custom
值作为@JsonInclude
.
来自
If you use Jackson 2.9+ version, you could try with a Include.Custom
value for @JsonInclude
.
From the JsonInclude.CUSTOM
specification :
表示单独的
filter
对象的值(由JsonInclude.valueFilter()
表示值本身,和/或JsonInclude.contentFilter()
对于结构化类型的内容)应为 用于确定纳入标准.过滤对象的equals() 用值调用方法进行序列化;如果返回true,则值为 排除(即过滤掉);如果包含为假值.
Value that indicates that separate
filter
Object (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;
}
}
它与objects
和基元一起使用,并且在filter.equals()
方法中将基元包装到包装器中.
It works with objects
and primitives and it boxes primitives to wrappers in the filter.equals()
method.
这篇关于Jackson序列化忽略负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!