Explain Codes LogoExplain Codes Logo

Gson ignoring map entries with value=null

java
json-serialization
gson
custom-serialization
Alex KataevbyAlex Kataev·Sep 23, 2024
TLDR

To serialize null values Gson provides .serializeNulls() method:

Gson gson = new GsonBuilder().serializeNulls().create(); String json = gson.toJson(new HashMap<String, Object>() {{ put("key1", null); put("key2", "value2"); }});

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:

class CustomTypeAdapter extends TypeAdapter<YourClass> { @Override public void write(JsonWriter out, YourClass value) throws IOException { // Some serious serialization happening here // Don't forget to invite all party guests, including nulls! } @Override public YourClass read(JsonReader in) throws IOException { // YourClass is throwing a deserializing party here } } Gson gson = new GsonBuilder() .registerTypeAdapter(YourClass.class, new CustomTypeAdapter()) .serializeNulls() // null values fans club. .create();

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:

class Example { String key1 = "default"; String key2 = "default"; } Gson gson = new Gson(); Example example = gson.fromJson(json, Example.class);

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:

Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create(); // Who said elegance can't be compact?! Not me!

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.