RuntimeTypeAdapterFactory
Adapts values whose runtime type may differ from their declaration type. This is necessary when a field's type is not the same type that GSON should create when deserializing that field. For example, consider these types:
abstract class Shape {
int x;
int y;
}
class Circle extends Shape {
int radius;
}
class Rectangle extends Shape {
int width;
int height;
}
class Diamond extends Shape {
int width;
int height;
}
class Drawing {
Shape bottomShape;
Shape topShape;
}
Content copied to clipboard
Without additional type information, the serialized JSON is ambiguous. Is the bottom shape in this drawing a rectangle or a diamond?
{
"bottomShape": {
"width": 10,
"height": 5,
"x": 0,
"y": 0
},
"topShape": {
"radius": 2,
"x": 4,
"y": 1
}
}Content copied to clipboard
{
"bottomShape": {
"type": "Diamond",
"width": 10,
"height": 5,
"x": 0,
"y": 0
},
"topShape": {
"type": "Circle",
"radius": 2,
"x": 4,
"y": 1
}
}Content copied to clipboard
"type") and the type labels (
"Rectangle") are configurable. Registering Types
Create aRuntimeTypeAdapterFactory by passing the base type and type field name to the of factory method. If you don't supply an explicit type field name, "type" will be used.
RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory
= RuntimeTypeAdapterFactory.of(Shape.class, "type");
Content copied to clipboard
shapeAdapterFactory.registerSubtype(Rectangle.class, "Rectangle");
shapeAdapterFactory.registerSubtype(Circle.class, "Circle");
shapeAdapterFactory.registerSubtype(Diamond.class, "Diamond");
Content copied to clipboard
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(shapeAdapterFactory)
.create();
Content copied to clipboard
GsonBuilder, this API supports chaining:
RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class)
.registerSubtype(Rectangle.class)
.registerSubtype(Circle.class)
.registerSubtype(Diamond.class);
Content copied to clipboard
Serialization and deserialization
In order to serialize and deserialize a polymorphic object, you must specify the base type explicitly.
Diamond diamond = new Diamond();
String json = gson.toJson(diamond, Shape.class);
Content copied to clipboard
Shape shape = gson.fromJson(json, Shape.class);
Content copied to clipboard
Functions
Link copied to clipboard
Link copied to clipboard
Registers
type identified by its simple name.Registers
type identified by label.