问题描述
我想为模型上的某些字段设置默认值,因此,如果在反序列化期间我的json缺少字段,则将使用这些默认值。
我想了解的是这样做的最佳实践,以及原因。
我应该在模型的设置器中添加null控件,我应该使用try catch查找任何情况,我应该扩展和修改typeAdapter(此解决方案对我来说似乎很冗长,让我知道我是否是错的)还是有更好的解决方案?
I would like to set default values for some fields on my model, so if during deserialization my json has missing fields, those default values are used.What I would like to understand which is the best practice to do this, and why.I should add the control of null in the setters of my model, I should use the try catch to find any cases, I should extend and modify typeAdapter (this solution seems very verbose to me, let me know if I'm wrong) or there is a even better solution?
推荐答案
如果这些内容根本无法在JSON数据中使用,
If those won't be available be in JSON data at all, then just initiate the variables.
private int id = -1;
private String name = "User not available";
如果有可能得到 null
值,然后在吸气剂中检查
If there is a probability that you might get null
values, then check for it in getters
private String DEFAULT_NAME = "User not available";
private String name;
public String getName(){
if(null == name) return DEFAULT_NAME;
return name;
}
这篇关于使用GSON的空字段的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!