gpt4 book ai didi

java - jackson 序列化忽略负值

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:47 28 4
gpt4 key购买 nike

我有一个这样的对象:

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_NULLInclude.NON_EMPTYInclude.NON_DEFAULT 一起使用,但是它们都不符合我的问题。

我能否以某种方式将 @JsonInclude 与我的条件 number >= 0 一起使用以仅在非负值时包含该值?或者有其他解决方案可以实现吗?

最佳答案

如果您使用 Jackson 2.9+ 版本,您可以尝试使用 @JsonIncludeInclude.Custom 值。
来自 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.

这是一种比定义自定义序列化程序更具体、更具声明性的方法。

@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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com