首页 > 解决方案 > 是否可以使用 gson 中的注释设置默认值?

问题描述

是否可以使用注释为 Gson 属性设置默认值?我想在反序列化/序列化之后使用这个默认值

@SerializedName(key = "a", defaultValue = "hi")
public String a;

@SerializedName("b")
public String b;

标签: androidgsonretrofit2

解决方案


如果变量为 null,您可以在 setter 方法中设置默认值

@SerializedName("yourVariable")
public String yourVariable;

public String getYourVariable(){
    if(yourVariable==null){
       return defaultValue;
    }
    return yourVariable;
}

推荐阅读