Jackson serialization: Ignore uninitialised int

12,548

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

Share:
12,548
Shiri
Author by

Shiri

Updated on July 04, 2022

Comments

  • Shiri
    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 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.

  • Shiri
    Shiri over 8 years
    I've tried this, the conversion, String json = mapper.writeValueAsString(data) just fails in this case.
  • Shiri
    Shiri over 8 years
    This 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
    dguay over 8 years
    Well it's hard to help without seeing the class you're trying to serialize. You shouldn't have problem with Integer.
  • Brian
    Brian over 5 years
    @Shiri The accessor methods should be updated as well to return/set Integer class.