How do I retain the default values of field in a deserialized object?
This is a known, currently open issue: https://github.com/google/gson/issues/513
Gson constructs the values of fields in deserialized objects with reflection, so it will set the values based on what's in the JSON only. Until Google provides a fix for this issue, there isn't that much you can do.
There are a number of workaround objects you have in the meantime:
- Wrap the fields in getters, and lazily load the value. This is a good way (and my personal recommendation) to do it if a field is never ever allowed to be
null
, but they do need to be mutable. - Mark the default fields as
final
. This a good way to do it if they are immutable. - Create a custom
ExclusionStrategy
, and mark the particular fields that should be ignored usingFieldAttributes
- This is the most versatile of the options but also the most code.
- Deserialize your POJO using just the fields that don't exist, and then compose that data structure with a new one that has the default values.
I agree that all of these have drawbacks, but as I said above, this is an open issue with Gson.