m2o
m2o

Reputation: 6694

Gson ignoring map entries with value=null

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?

Upvotes: 156

Views: 95589

Answers (1)

Alois Cochard
Alois Cochard

Reputation: 9862

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();

Upvotes: 345

Related Questions