我有一个这样的对象:
public class MyObject {
private String name;
private int number;
// ...
}
而且我只想在值不为负(number >= 0
)时包含 number
。
在研究过程中我发现了 Jackson serialization: ignore empty values (or null)和 Jackson serialization: Ignore uninitialised int .两者都将 @JsonInclude
注释与 Include.NON_NULL
、Include.NON_EMPTY
或 Include.NON_DEFAULT
一起使用,但是它们都不符合我的问题。
我能否以某种方式将 @JsonInclude
与我的条件 number >= 0
一起使用以仅在非负值时包含该值?或者有其他解决方案可以实现吗?
最佳答案
如果您使用 Jackson 2.9+ 版本,您可以尝试使用 @JsonInclude
的 Include.Custom
值。
来自 the JsonInclude.CUSTOM
specification :
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.
这是一种比定义自定义序列化程序更具体、更具声明性的方法。
@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;
}
}
它与对象
和基元一起工作,它在 filter.equals()
方法中将基元包装到包装器中。
关于java - jackson 序列化忽略负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56493606/