简体   繁体   中英

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.

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.

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{
    ...
}

Change int to Integer .

Otherwise no, it is not possible to have int variable with null in any way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM