Jackson序列化忽略负值 [英] Jackson serialization ignore negative values

查看:157
本文介绍了Jackson序列化忽略负值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的对象:

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 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;
    }
}

它与objects和基元一起使用,并且在filter.equals()方法中将基元包装到包装器中.

It works with objectsand primitives and it boxes primitives to wrappers in the filter.equals() method.

这篇关于Jackson序列化忽略负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆