The example below shows a class (Club) that contains a collection of an abstract class (Member). I\'m confused as to whether I need a TypeAdapter or JsonDeserializer to make
You can do both. Which one you pick depends really on potential performance impact, and how much code are willing to write.
Deserializers are more expensive. That is because the input to deserializer is a json tree, and GSon will have to create a full JsonElement subtree of the property that matches your class, before it can pass it to your deserializer. If your classes have a lot of nesting, that cost increases. For plain objects, it will be negligible.
It seems that you will know which class to create based on the value of type
property that will be included in target object. Your deserializer will need to
JsonElement
object, read the type
property, determine the typecontext.deserialize()
with the class and the same element that was passed to youYour type adapter will have to be more complex. The input to the type adapter is stream, not an element/subtree. You can load the next value entirely from the stream, parse it, and then do exactly what deserializer did, which doesn't make sense and you can just use the deserializer interface. Alternatively, you can read the stream, see what properties there are, save them into local variables, until you get to the type
property (you can't predict its location), then finish reading the remainder of the properties, and create your final Gold
/Silver
objects based on type, and all the properties read and saved.