You can do it by gson custom JsonSerializer like this
public class HumanSerializer implements JsonSerializer<Human> {
@Override
public JsonElement serialize(final Human human, final Type type, final JsonSerializationContext context) {
final JsonObject json = new JsonObject();
if(human instanceof Human)
json.addProperty("type", "Human");
if(human instanceof Worker)
json.addProperty("type", "Worker");
if(human instanceof Student)
json.addProperty("type", "Student");
json.addProperty("name", human.getName());
return json;
}
}
finally you have to register your classes and then serialize it
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Human.class,new HumanSerializer());
gsonBuilder.registerTypeAdapter(Worker.class,new HumanSerializer());
gsonBuilder.registerTypeAdapter(Student.class,new HumanSerializer());
final Gson gson = gsonBuilder.create();
Output
gson.toJson(new Worker("adam", "workplace"));
gson.toJson(new Human("Jhon"));
{"type":"Worker","name":"adam"}
{"type":"Human","name":"Jhon"}