Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First class support for polymorphism (subclasses!) #231

Open
GoogleCodeExporter opened this issue Apr 1, 2015 · 45 comments
Open

First class support for polymorphism (subclasses!) #231

GoogleCodeExporter opened this issue Apr 1, 2015 · 45 comments

Comments

@GoogleCodeExporter
Copy link

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<Shape> shapes = new ArrayList<Shape>();
    shapes.add(r);
    shapes.add(c);

    Gson gson = new GsonBuilder()
        .create();

    String json = gson.toJson(shapes, new TypeToken<List<Shape>>() {}.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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant