Suppose to have an abstract class, say A
, and two non-abstract subclasses, say A1
and A2
. I want to "deserialize" them from a json format by using the GSON library.
E.g. I get an array of A
objects.
int n = ...;
A[] list = new A[n];
A[0] = new A1(....);
A[1] = new A2(....);
...
which someone converted to a JSON string as follows:
String json = (new Gson()).toJson(list);
Finally, if I try to deserialize as follows
A[] deserializedList = (new Gson()).fromJson(json, A[].class);
then I has got an error, since the GSON default deserializer finds an abstract class (i.e. A
) and it is not capable of guessing the subclass type.
How can I solve this?
PS: I read about custom deserializer, but I don't understand how to use them in this case.