java - jackson 序列化忽略负值

标签 java json serialization jackson

我有一个这样的对象:

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/

相关文章:

Java 泛型——需要解释

c# - 使用自定义格式序列化 JSON 字符串

c++ - 使用 QSettings 保存 QSpinBox 和 QComboBox 的组合

c# - 在 C# 中的二进制序列化中排除父对象

java - 复杂的 if() 或枚举?

java - @EJB注解

php - 使用 Zend_Http_Client 发送 json POST

javascript - 如何在 Angular 输入中保留换行符

JSON 字段设置为 null vs 字段不存在

java - OAuth2 spring 示例闪光和色调