2 Minutes To Code (β Version)

JSON and gson api - 2 minute tutorial

How to retain null fields of java object in json notation

We saw in the earlier examples in section "Convert object to JSON notation" that, if a java object contained an object reference to null, then the corresponding json notation did not contain that field.

However, if you need to retain that null field then you need to create a com.google.gson.Gson object using a com.google.gson.GsonBuilder object and configure it to serialze nulls as shown in line no. 10. Then, just use the toJson(Object) method to get the json form.
package com.techfundaes.gsonBag;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class RetainNull
	public static void main(String[] args)
		Gson gson = new GsonBuilder().serializeNulls().create();
		CollectionsBag collectionsBag = new CollectionsBag();
		String text = gson.toJson(collectionsBag);
If you run the above code, the json notation of CollectionsBag object will be printed as shown in the image below.

Notice that the TreeMap field gameAuthorMap of class com.techfundaes.gsonBag.CollectionsBag which was null is retained in the json form in the image above. Contrast this to the earlier example where null field was not retained in json notation.