T - The interface or abstract type to be serialized and deserialized with Gson.public class GsonInterfaceAdapter extends Object implements com.google.gson.TypeAdapterFactory
Gson interface adapter that makes it possible to serialize and deserialize polymorphic objects.
This adapter will capture all instances of baseClass and write them as
{"object-type":"class.name", "object-data":"data"}, allowing for correct serialization and deserialization of
polymorphic objects. The following types will not be captured by the adapter (i.e. they will be written by the
default GSON writer):
- Primitives and boxed primitives
- Arrays
- Collections
- Maps
Additionally, generic classes (e.g. class MyClass
To use:
MyClass object = new MyClass();
Gson gson = GsonInterfaceAdapter.getGson(MyBaseClass.class);
String json = gson.toJson(object);
Myclass object2 = gson.fromJson(json, MyClass.class);
Note: a useful case is GsonInterfaceAdapter.getGson(Object.class), which will correctly serialize / deserialize all types except for java generics.
| Modifier and Type | Field and Description |
|---|---|
protected static String |
OBJECT_DATA |
protected static String |
OBJECT_TYPE |
| Constructor and Description |
|---|
GsonInterfaceAdapter() |
| Modifier and Type | Method and Description |
|---|---|
<R> com.google.gson.TypeAdapter<R> |
create(com.google.gson.Gson gson,
com.google.gson.reflect.TypeToken<R> type) |
static <T> com.google.gson.Gson |
getGson(Class<T> clazz) |
protected static final String OBJECT_TYPE
protected static final String OBJECT_DATA
public <R> com.google.gson.TypeAdapter<R> create(com.google.gson.Gson gson,
com.google.gson.reflect.TypeToken<R> type)
create in interface com.google.gson.TypeAdapterFactorypublic static <T> com.google.gson.Gson getGson(Class<T> clazz)