Custom Instance Creators in GSON


By default GSON will try to create an instance of a given class by calling the no-arg constructor of that class. However, if a given class does not have a default constructor, or we want to do some default configuration of the instance, or if we want to create an instance of a subclass instead, we need to create and register your own instance creator.

A GSON instance creator is simply an object factory. An instance creator has to implement the InstanceCreator interface (com.google.gson.InstanceCreator).

Check This InstanceCreator implementation example:

package com.tutorialtous.gson;
import java.lang.reflect.Type;
import java.util.LinkedList;
import com.google.gson.InstanceCreator;
public class PlayerCreator implements InstanceCreator<Player> {
	@Override
	public Player createInstance(Type type) {
		Player player = new Player();
		player.gender = "Male";//default binding if none specified
		player.gamesplayed = new LinkedList<>();
		return player;
	}
}						

GsonBuilder gsonBuilder = new GsonBuilder();
gsonbuilder.registerTypeAdapter(Player.class, new PlayerCreator());
Gson gson  = gsonBuilder.create();

Now the Gson instance will use the PlayerCreator instance to create Player instances. We can prove that to yourself by running this code (after the PlayerCreator has been registered):


package com.tutorialtous.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonCustomInstance {
	public static void main(String[] args) {
		String jsonwithoutgender = "{\"name\":\"Alex\"}";
		String jsonwithgender = "{\"name\":\"Madona\",\"gender\":\"Female \"}";
		Player player = null;
		GsonBuilder gsonbuilder = new GsonBuilder();
		gsonbuilder.registerTypeAdapter(Player.class, new PlayerCreator());
		Gson gson = gsonbuilder.create();
		player = gson.fromJson(jsonwithoutgender, Player.class);
		System.out.println(player.name + "\t" + player.gender);
		player = gson.fromJson(jsonwithgender, Player.class);
		System.out.println(player.name + "\t" + player.gender);
	}
}

output

Alex	Male
Madona	Female 

In the above example we have two strings 1) jsonwithoutgender 2)jsonwithgender.
when we run the above prog the default gender will be initilized to 'Male' due to PlayerCreator.

so jsonwithoutgender will get gender as 'Male' and for the other string 'jsonwithgender' gender is mentioned it will overwrite with default value. as a result output will be

Alex	Male
Madona	Female