How to configure to remove null objects in json response using GSON in SpringREST

If you have a Spring web service that returns a JSON response. Suppose, your response is of below format:-

{“name”:null,”staffName”:[“kfc-kampar”,”smith”]}

Obviously returning null values is not a good practice if you think from client perspective, as client needs further null handling. That’s cumbersome, so best solution is to suppress/remove those fields from response that contains null values.

{“staffName”:[“kfc-kampar”,”smith”]}

The below solution is for those who are using GSON as JSON implementation in Spring REST framework with JAVA configuration.
In your Web App configuration you need to override configureMessageConverters() method.

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
GsonHttpMessageConverter msgConverter = new GsonHttpMessageConverter();
Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Collection.class, new 
CollectionAdapterForGson(getGson()))
           .registerTypeHierarchyAdapter(Map.class, new MapAdapterForGson(getGson())).setPrettyPrinting().create();
msgConverter.setGson(gson);
converters.add(msgConverter);
}

Now for preparing your response mostly people use Collection or Map objects. So we will be registering adapters for Collection and Map that will have implementation for removing fields that have null values. These adapters will be called for each and every response.

import java.lang.reflect.Type;
import java.util.Collection;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class CollectionAdapterForGson implements JsonSerializer<Collection<?>>{
	
	private Gson gson;
	
	public CollectionAdapterForGson(Gson gson) {
		this.gson = gson;
	}
	
	  @Override
	  public JsonElement serialize(Collection<?> src, Type typeOfSrc, JsonSerializationContext context) {
	    if (src == null || src.isEmpty()) // exclusion is made here
	      return null;

	    JsonElement element = gson.toJsonTree(src, src.getClass());
	    return element;
	  }
}
import java.lang.reflect.Type;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class MapAdapterForGson implements JsonSerializer<Map<String, Object>>{

	private Gson gson;
	
	public MapAdapterForGson(Gson gson) {
		this.gson = gson;
	}

	@Override
	public JsonElement serialize(Map<String, Object> src, Type typeOfSrc, JsonSerializationContext context) {
		    if (src == null || src.isEmpty()) // exclusion is made here
		      return null;

	    JsonElement element = gson.toJsonTree(src, src.getClass());
	    return element;
	}
}

That’s it now are free from null value fields.
Happy coding!