Handling polymorphism with Gson

Ilia Sharipov
2 min readJul 21, 2020

--

Photo by Carlo D’Agnolo on Unsplash

Sometimes you need to deserialize JSON to a concrete class that inherits from an abstract class.

Gson JSON library does not provide the only and correct way to do this.

If I’m wrong, please tell me about it, and I will delete this post immediately.

Of course, I won’t delete my post, because it’s my creation, my child. If you don’t like my idea, or if you know something that I don’t know or if you have some ideas on how to work with polymorphism using Gson Json library right, please let me know 😀 and leave a couple of useful comments below the post.

What we have

Class diagram

We have employees

And we’re trying to deserialize JSON to Employee object.

But when we try to deserialize it (please, don’t worry that Employee is an abstract class, to deserialize it without any problems I removed abstract keyword):

we get the expected result:

Debug

All employees are identical, and we lost a lot of information, many employees will remain without any salary, sad😢.

I suggest very stupidly but on the other hand an elementary solution:

  1. Every individual type in the Employee model should have a key attribute. For example, Hourly employees can have an “hourly” key attribute.
  2. Main abstract Employee class should be annotated with an annotation that will contain information about subtypes — including key attributes and class types.
  3. Processor — of course, we need a processor that should read information about subtypes and decide what type to use for deserialization.

As a processor, we will use the mechanism that is already available in the Gson — JsonDeserializer.

Also, we need two annotations:

Let’s annotate Employee class with annotations above:

Imagine that JSON already contains type property.

And the last thing we need to do, register JsonDeserializer as a type adapter:

Thank you for wasting your time.

Source code of PolymorphDeserializer you can find in my Github repository, also it contains Gson + Retrofit + Wiremock example — io.github.isharipov.gson.adapters.PolymorphDeserializerTest and Employee model.

--

--