2

Could someone tell why the following suggested solution to set default value on object while deserializing is working:
https://stackoverflow.com/a/30219311/35917

As per my understanding GSON does not use getter and setter method to set/fetch object property. I tried the solution on my system and it does not seem to be working.

Regards,

Tarun
  • 3,162
  • 3
  • 29
  • 45

2 Answers2

3

Well, it doesn't, but you would want to access fields of the object you are trying to deserialize. And you will probably do so using getters.

In the provided answer getter will set a default value to the field if it finds that field is null. It's not really related go GSON, but can be applied to any java class.

rxn1d
  • 1,236
  • 6
  • 18
  • oh okay, I think there is no other way (except writing custom deserializer) to provide default value via GSON. – Tarun Apr 02 '20 at 11:31
  • I found a similar question. The solution is still the same, unfortunately. https://stackoverflow.com/questions/52314615/default-value-for-null-fields-using-gson – rxn1d Apr 02 '20 at 11:33
2

That answer uses the default value to populate the data if it is null during retrieve and assigning value. GOSN has nothing to do with it. GSON will simply pick whatever the value of that field and deserialize and serialize it.