Suppose I have a class structure like this (much simpler than my use case):
abstract class Animal {
}
class Dog extends Animal {
String call = "woof";
}
class Bird extends Animal {
int numWings = 2;
}
I then serialize a Dog and get this:
However, when I try to deserialize it:
gson.fromJson(dogJson, Animal.class)
it naturally can't tell that it's a dog, and tries to instantiate an Animal:
java.lang.RuntimeException: Failed to invoke Animal() with no args
It would be useful if, when I serialize a dog as an animal, because Animal is abstract (or an interface, same deal would apply), I get output more like this:
{"type":"Dog","value":{"call":"woof"}}
and then when it is deserialized as an animal, Gson could recognize that this is the Dog subclass and deserialize accordingly. It would also be helpful if I could establish my own name-to-class relationships so that I don't write out "super.long.package.name.Dog" every time.
Is there any support for this in Gson, or is it not a common enough use case? And if there isn't, and I wrote my own solution, would I be able to add it to Gson?