Default value for null fields using GSON

。_饼干妹妹 提交于 2020-07-22 09:19:41

问题


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?


回答1:


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";

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


来源:https://stackoverflow.com/questions/52314615/default-value-for-null-fields-using-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!