google / google/gson

First class support for polymorphism (subclasses!)

Open
#231 7 comments 0 reactions 0 assignees View on GitHub
auto-migrated enhancement Priority-Medium Type-Enhancement
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.