How do you handle polymorphic types in GSON?
A) By using the @JsonAdapter annotation
B) By using the @SerializedName annotation
C) By using the @Expose annotation
D) By using the @JsonInclude annotation
Answer:
A) By using the @JsonAdapter annotation
Explanation:
In GSON, you can handle polymorphic types by using the @JsonAdapter
annotation in combination with a custom serializer or deserializer. This allows you to specify how to serialize and deserialize different subtypes of a polymorphic object.
For example:
@JsonAdapter(AnimalAdapter.class)
public class Animal { ... }
public class AnimalAdapter extends TypeAdapter<Animal> {
@Override
public void write(JsonWriter out, Animal value) throws IOException {
// custom serialization logic
}
@Override
public Animal read(JsonReader in) throws IOException {
// custom deserialization logic
return null;
}
}
In this example, the @JsonAdapter
annotation is used to associate the AnimalAdapter
class with the Animal
class. The adapter handles the serialization and deserialization of different animal subtypes.