简体   繁体   中英

Java POJO JSON ignore default field annotation

How can I seperate a JSON field that gets actually set to int value 0 versus set to 0 by default? I want to see the json field with actual value: '0', but ignore it when its not set at all (but still ends up as 0).

I am currently testing this on my int field variable:

@JsonInclude(JsonInclude.Include.NON_DEFAULT)

but it ignores every 0 value for that field in my json.

There is not a way to check whether the int value "0" is set by default or not in Java. Instead you can try one of these options.

  1. Use Integer - When using an Integer instead int, you can differntiate this easily. The Integer will be null if a value is not set. (I prefer this way)
  2. Use int and use a boolean field in order to mark whether a value is set to the int or not. You can set the value of the boolean to "true" in the setter method of your int field. By looking at the boolean value you can differentiate whether a value is set to the int field or not.
    private int foo;
    
    private boolean isFooSet;
    
    public void setFoo(int value){
        this.foo = value;
        this.isFooSet = true;
    }

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