Jackson序列化:忽略未初始化的int [英] Jackson serialization: Ignore uninitialised int
问题描述
现在首先,我已经在该网站上阅读了其他答案以及有关杰克逊序列化的其他答案,但它们都提供了忽略null
字段的方法.但是,在Java中,int
不能为null
.
Now first off, I've read some other answers on this site and others about jackson serialisation but they all provide methods for ignoring null
fields. In Java, however, int
cannot be null
.
我正在尝试ObjectMap
一个Java对象转换为Json
,但是忽略任何null
字段.这适用于字符串,但是int
如果未初始化,最终将采用0
的值,并且由于0
不是null
,因此不会忽略该字段.
I am trying to ObjectMap
a java object to convert to Json
but to ignore any null
fields. This works for strings but int
s end up taking on a value of 0
if uninitialised, and since 0
is not null
the field is not ignored.
private ObjectWriter mapper = new ObjectMapper().writer();
private myClass data = new myClass(); //class contains a string and int variable
data.setNumber(someInt); //set values
data.setString(someString);
String Json = mapper.writeValueAsString(data);
请问有人对此有何启示?
Can anyone shed some light on this please?
为澄清起见,我尝试使用Integer
类作为数据类型,但导致转换为Json
字符串时引发JsonProcessingException.
To clarify, I have tried using the Integer
class as the data type but causes the conversion to a Json
string to throw a JsonProcessingException.
推荐答案
使用Jackson JsonInclude批注:
Using the Jackson JsonInclude annotation:
@JsonInclude(Include.NON_DEFAULT)
解决以下问题:未分配的原始类型始终采用默认值;在这种情况下,未分配的int
变为0
,随后将被忽略.
works around the problem where unassigned primitive types always assumes a default value; in this case, unassigned int
s become 0
and are subsequently ignored.
这篇关于Jackson序列化:忽略未初始化的int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!