Java – set the default value to a variable when deserializing with gson

I'm trying to convert JSON to Java objects When a value of a pair is empty, some default values should be set

This is my POJO:

public class Student {      
    String rollNo;
    String name;
    String contact;
    String school;

    public String getRollNo() {
        return rollNo;
    }
    public void setRollNo(String rollNo) {
        this.rollNo = rollNo;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSchool() {
        return school;
    }
    public void setSchool(String school) {
        this.school = school;
    }
}

JSON object example

{
  "rollNo":"123","name":"Tony","school":null
}

So if the school is empty, I should make it a default value, such as "school": "XXX" How to configure gson when deserializing objects?

Solution

If NULL is in JSON, gson will override any default values you may set in POJO You can create a custom deserializer trouble, but it may be excessive in this case

I think the simplest (and arguably the best use case for you) thing 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 you have to change the code in order to change the default value If you want the default value to be customizable, you should use the custom deserializer linked above

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>