有条件地忽略Jackson的原始类型字段 [英] Conditionally ignore primitive typed fields with Jackson
问题描述
简短问题:有没有办法根据杰克逊的价值选择序列化某个字段?有没有办法告诉杰克逊,比如如果某个整数字段的值为0,请不要序列化它。
Short Question: Is there a way to optionally serialize a field depending on it's value in jackson? Is there a way to tell jackson, something like "if a certain integer field's value is 0, don't serialize it."
(如果你得到了什么,请跳过以下内容我的意思是)
(skip the following if you get what I mean)
长问题又名为什么我要做这样的事情:
Say我有一个Spring MVC模型类
Long Question aka Why would I want to do such a thing: Say I have a Spring MVC model class
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Foo {
int a0;
int a1;
.
.
.
int a99;
String c;
//getters and setters
}
对象 Foo
,所有 int
将初始化为0, String
到 null
。因此,如果我序列化这个对象,我只会在结果中得到 int
,所有都设置为0,这要归功于 @JsonSerialize(include = JsonSerialize.Inclusion) .NON_NULL)
。
For a new object of Foo
, all int
will get initialized to 0, The String
to null
. So if I serialize this object, I will only get int
s in result, all set to 0, thanks to @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
.
在实际操作中,假设我只需回复只有某些的a1 .. .a99,比较a20到a26,设定一些有意义的价值(对我而言,它不是0)。发送那些字段是明智的,对吧?
In actual operation, say I have to reply with only some of the a1...a99, say a20 to a26, set to some meaningful value (to me it's something other than 0). It would be wise to send only those fields, right?
为了达到这个目的,我总是可以改变我的 int
声明到整数
。但是,我有很多关于整数的数值计算,并且在网上稍微思考并遇到像这样的链接这个和这个,我有点想坚持原始类型。是否存在满足我需求的解决方案?
To achieve this, I can always change my int
declarations to Integer
. However, I have a lot of numerical computations over ints, and pondering over the net a bit and coming across links like this and this, I kinda want to stick to primitive types. Does there exist a solution satisfying both my needs?
推荐答案
考虑 JSON过滤器。我认为你需要实现自己的 BeanPropertyFilter
的实例。
Consider JSON Filters. I think you will need to implement your own instance of BeanPropertyFilter
though.
这篇关于有条件地忽略Jackson的原始类型字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!