Polymorphism Support?

1,308 views
Skip to first unread message

Derek Peirce

unread,
May 13, 2015, 2:47:08 AM5/13/15
to googl...@googlegroups.com
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:
{"call":"woof"}

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?

James Wald

unread,
May 15, 2015, 11:45:58 AM5/15/15
to googl...@googlegroups.com
You can get this behavior using the RuntimeTypeAdapterFactory:

https://github.com/google/gson/blob/master/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java

This allows you to map concrete classes to type labels and vice versa. Note that you'll have to copy this source into your project because gson-extras is not published on Maven Central.

Derek Peirce

unread,
May 16, 2015, 4:30:55 PM5/16/15
to googl...@googlegroups.com
Thanks! That's exactly what I was looking for!

Danilo Pianini

unread,
Sep 8, 2016, 11:21:48 AM9/8/16
to google-gson
I took some time to publish gson-extras on Central. Their current git (as I write) is published as org.danilopianini:gson-extras:0.1.0.
Reply all
Reply to author
Forward
0 new messages