Adapters for Gson JSON library
Why use Gson adapters?
Sometimes we need to deserialize a JSON to a concrete class which inherits from an abstract class.
Gson + Retrofit + Wiremock example - io.github.isharipov.gson.adapters.PolymorphDeserializerTest
Library provides a set of annotations you can apply to abstract class. Also, library contains Polymorph Deserializer which do the trick.
To tell the deserializer which implementation to use to deserialization, annotate abstract class with @JsonType annotation and provide information about subtipes through set of @JsonSubtype annotations.
@JsonType(
property = "type",
subtypes = {
@JsonSubtype(clazz = CommissionEmployee.class, name = "commission"),
@JsonSubtype(clazz = HourlyEmployee.class, name = "hourly"),
@JsonSubtype(clazz = SalariedEmployee.class, name = "salaried")
}
)
public abstract class Employee {
private final String id;
private final String type;
...
Gson gson = new GsonBuilder()
.registerTypeAdapter(Employee.class, new PolymorphDeserializer<Employee>())
.create();
Pay attention, that in each implementation you should have to have a magic field, based on which, the Deserializer will determine the final implementation.
Gradle
dependencies {
implementation("io.github.isharipov:gson-adapters:0.1")
}
Maven
<dependencies>
<dependency>
<groupId>io.github.isharipov</groupId>
<artifactId>gson-adapters</artifactId>
<version>0.1</version>
</dependency>
<dependencies>
Requirements
Library requires Java 1.8 or later.