Home > Mobile >  Java POJO JSON ignore default field annotation
Java POJO JSON ignore default field annotation

Time:04-12

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.

CodePudding user response:

Use a pointer for the fields, so that the zero value of the JSON type can be differentiated from the missing value.

type Test struct {
    String  *string `json:"string,omitempty"`
    Integer *int    `json:"integer,omitempty"`
}

https://play.golang.org/p/yvYSHxubLy

CodePudding user response:

Before saving value check if it's null. If it is null then set it to 0. Hopefully it'll give you your answer.

CodePudding user response:

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;
    }
  • Related