Gson ignoring map entries with value=null
To serialize null
values Gson provides .serializeNulls()
method:
The json
string will now include {"key1":null,"key2":"value2"}
. It ensures inclusion of null
entries.
TypeAdapter: Taking charge of complex serialization
Sometimes, dealing with complex objects or needing custom serialization logic, you might need to write a bit more code. Implement a TypeAdapter
or JsonSerializer
for fine grained control:
Your TypeAdapter
is now the master of ceremony, deciding how each type should be serialized, handling null
values, and thinking about exceptions.
Decoding JSON: Dealing with default values
When decoding the JSON back to Java, let's consider default values for our fields:
If your json
has null
for key1
, Example.key1
will remain "default"
, unless during encoding we called our helpful friend .serializeNulls()
and explicitly set a null
for that key.
Keep JSON Compact and Neat
We can keep our JSON compact, even when including null
values:
setPrettyPrinting
is purely optional; omit to keep JSON compact, no line breaks, no indentation, just pure efficient JSON!
Props to the Community
It's pleasant to acknowledge insights, useful answers and discussions in the community that guided us to the right Gson
configuration path.
Beyond Basic
The Gson User Guide and repository issues can be a great resource for deep-diving, advanced use cases and understanding null
values.
Not a Bug, but a Feature!
Remember the issue of Gson
ignoring null
values in a Map
is not a bug, it's a feature! You, as developer, have full control over Gson
's behaviour.
Was this article helpful?