You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
The text was updated successfully, but these errors were encountered:
Original issue reported on code.google.com by
limpbizkit
on 28 Aug 2010 at 6:00The text was updated successfully, but these errors were encountered: