Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for null fields using GSON

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?

like image 508
pixelatedCat Avatar asked Oct 28 '25 22:10

pixelatedCat


1 Answers

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; 
}
like image 113
isamirkhaan1 Avatar answered Oct 31 '25 14:10

isamirkhaan1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!