Skip to content Skip to sidebar Skip to footer

How Does Polymorphism Work With Gson (retrofit)

Here is my Retrofit instance: @Provides @Singleton ApiManager provideApiManager() { RxJava2CallAdapterFactory rxAdapter = RxJava2CallAdapterFactory.create(); OkHttpClient

Solution 1:

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:

publicclassAnimal {
    protectedString name;
    protectedStringtype;

    publicAnimal(String name, Stringtype) {
        this.name = name;
        this.type = type;
    }
}

publicclassDogextendsAnimal {
    privateboolean playsCatch;

    publicDog(String name, boolean playsCatch) {
        super(name, "dog");
        this.playsCatch = playsCatch;
    }
}

publicclassCatextendsAnimal {
    privateboolean chasesLaser;

    publicCat(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 = newGsonBuilder()
    .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.

Post a Comment for "How Does Polymorphism Work With Gson (retrofit)"