Gson ignoring map entries with value=null

JavaJsonGson

Java Problem Overview


Gson gson = new Gson();

Map<String,Object> map = new HashMap<String, Object>();
map.put("a", 1);
map.put("b", null);

System.out.println(gson.toJson(map)); //prints {"a":1}

How do I get it to include all entries?

Java Solutions


Solution 1 - Java

See Gson User Guide - Null Object Support:

> The default behaviour that is implemented in Gson is that null object fields are ignored. This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java form. > > Here's how you would configure a Gson instance to output null: > > Gson gson = new GsonBuilder().serializeNulls().create();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionm2oView Question on Stackoverflow
Solution 1 - JavaAlois CochardView Answer on Stackoverflow