You must create a RuntimeTypeAdapterFactory for the objects AbstractMessage, TextMessage and ImageMessage and then you must set it into the gson instance.
Suppose that you have those objects:
public class Animal {
protected String name;
protected String type;
public Animal(String name, String type) {
this.name = name;
this.type = type;
}
}
public class Dog extends Animal {
private boolean playsCatch;
public Dog(String name, boolean playsCatch) {
super(name, "dog");
this.playsCatch = playsCatch;
}
}
public class Cat extends Animal {
private boolean chasesLaser;
public Cat(String name, boolean chasesLaser) {
super(name, "cat");
this.chasesLaser = chasesLaser;
}
}
This below is the RuntimeTypeAdapter that you need in order to deserialize (and serialize) correctly those objects:
RuntimeTypeAdapterFactory<Animal> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory
.of(Animal.class, "type")
.registerSubtype(Dog.class, "dog")
.registerSubtype(Cat.class, "cat");
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(runtimeTypeAdapterFactory)
.create();
The class RuntimeTypeAdapterFactory.java is not shipped with the Gson package, so you have to download it manually.
You can read more about the runtime adapter here and here
Please note that the title of your question should be "Polymorphism with Gson"
I hope it helps.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…