Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ints 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.

like image 338
Shiri Avatar asked Oct 27 '15 15:10

Shiri


People also ask

How do you tell Jackson to ignore a field during serialization?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

How do I ignore null values in Jackson?

In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.

How do I ignore properties in Jackson?

The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.


2 Answers

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.

like image 67
Shiri Avatar answered Sep 19 '22 20:09

Shiri


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{
    ...
}
like image 41
dguay Avatar answered Sep 17 '22 20:09

dguay