First class support for polymorphism (subclasses!)
- Dominant language
- Java
- Stars
- 24.2k
- Forks
- 4.5k
- Avg merge
- 6d 4h
- Merged PRs (30d)
- 12
Description
```
GSON always operates on the static type of an object. It has no mechanism to
operate on the object's runtime type.
It would be handy if GsonBuilder permitted a way to specify the known
subclasses of a type. Then at serialization/deserialization these fields could
be included:
public void testPolymorphism() {
Rectangle r = new Rectangle();
r.width = 5;
r.height = 7;
Circle c = new Circle();
c.radius = 3;
List shapes = new ArrayList();
shapes.add(r);
shapes.add(c);
Gson gson = new GsonBuilder()
.create();
String json = gson.toJson(shapes, new TypeToken>() {}.getType());
assertEquals("[{\"width\":5,\"height\":7},{\"radius\":3}]", json);
}
static class Shape {}
static class Rectangle extends Shape {
int width;
int height;
}
static class Circle extends Shape {
int radius;
}
It would be extra awesome if it could use the set of fields in a stream to
infer the type to instantiate. In the example above, it could use that the
'radius' field as evidence that the runtime type should be a Circle. Or perhaps
this could be user-configured too, such as this:
new GsonBuilder()
.runtimeType(Shape.class, Circle.class, "radius")
.runtimeType(Shape.class, Rectangle.class, "width", "height")
.create();
```
Original issue reported on code.google.com by `limpbizkit` on 28 Aug 2010 at 6:00
Contributor guide
Assessment
This issue has not been assessed yet.