Jackson serialization: Ignore uninitialised int
Solution 1
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 int
s become 0
and are subsequently ignored.
Solution 2
Use int wrapper Integer
. This way you'll be able to use null
value.
Alternatively you can use Jackson's JsonInclude annotation to ignore null value when serializing.
@JsonInclude(Include.NON_NULL)
public class MyClass{
...
}
Solution 3
Change int
to Integer
.
Otherwise no, it is not possible to have int variable with null in any way.
Comments
-
Shiri almost 2 years
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 benull
.I am trying to
ObjectMap
a java object to convert toJson
but to ignore anynull
fields. This works for strings butint
s end up taking on a value of0
if uninitialised, and since0
is notnull
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 aJson
string to throw a JsonProcessingException. -
Shiri over 8 yearsI've tried this, the conversion,
String json = mapper.writeValueAsString(data)
just fails in this case. -
Shiri over 8 yearsThis is exactly what I'm talking about. The annotation only works for non_null but the int initialises as 0 by default because int cannot be null. I think my problem has something to do with Integer serialisation by Jackson like Libik was saying.
-
dguay over 8 yearsWell it's hard to help without seeing the class you're trying to serialize. You shouldn't have problem with
Integer
. -
Brian over 5 years@Shiri The accessor methods should be updated as well to return/set
Integer
class.