0
class Human {
   String name;
}

class Student extends Human {
   String college;
}

class Worker extends Human {
   String workPlace;
}

Suppose I want to serialize this using GSON.

Is it possible to add a pair "type" : "student" for each serialized Student instance (just as if type was a field of the class)? Similarly, add "type" : "worker" for each Worker instance?


A related question regards deserialization of such JSONS: Deserialize recursive polymorphic class in GSON

Community
  • 1
  • 1
Parobay
  • 2,549
  • 3
  • 24
  • 36
  • i think you want to make a generic class with type as variable check this answer http://stackoverflow.com/q/19173640/2334391 – jos Dec 02 '13 at 10:41

1 Answers1

0

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"}
Asif Bhutto
  • 3,916
  • 1
  • 24
  • 21