Shiri Shiri - 1 year ago 67
Java Question

Jackson serialization: Ignore uninitialised int

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
.

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?

EDIT: 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.

Answer Source

Using the Jackson JsonInclude annotation:

@JsonInclude(Include.NON_DEFAULT)

works around the problem where unassigned primitive types always assumes a default value; in this case, unassigned ints become 0 and are subsequently ignored.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download