Setting Default value to a variable when deseriali

2020-02-01 06:59发布

I am trying to convert JSON to Java object. When a certain value of a pair is null, it should be set with some default value.

Here 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;
    }
}

Example JSON object:

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

So if school is null, I should make this into a default value, such as "school":"XXX". How can I configure this with Gson while deserializing the objects?

标签: java json gson
3条回答
▲ chillily
2楼-- · 2020-02-01 07:21

I think that the way to do this is to either write your no-args constructor to fill in default values, or use a custom instance creator. The deserializer should then replace the default values for all attributes in the JSON object being deserialized.

查看更多
Summer. ? 凉城
3楼-- · 2020-02-01 07:27

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.

查看更多
欢心
4楼-- · 2020-02-01 07:30

You can simply make a universal function that checks for null

model.SchoolName= stringNullChecker(model.SchoolName);

public static String stringNullChecker(String val) {
        if (null == val) val = "";
        return val;
}
查看更多
登录 后发表回答