Setting Default value to a variable when deserializing using gson

If the null is in the JSON, Gson is going to override any defaults you might set in the POJO. You could go to the trouble of creating a custom deserializer, but that might be overkill in this case.

I think the easiest (and, arguably best given your use case) thing to do is the equivalent of Lazy Loading. For example:

private static final String DEFAULT_SCHOOL = "ABC Elementary";
public String getSchool() {
    if (school == null) school == DEFAULT_SCHOOL;
    return school;
}
public void setSchool(String school) {
    if (school == null) this.school = DEFAULT_SCHOOL;
    else this.school = school;
}

Note: The big problem with this solution is that in order to change the Defaults, you have to change the code. If you want the default value to be customizable, you should go with the custom deserializer as linked above.

Leave a Comment