GsonBuilder#registerTypeAdapter(Type, Object) method before Gson will be able to use
them.
Let us look at an example where defining an InstanceCreator might be useful. The Id
class defined below does not have a default no-args constructor.
public class Id<T> {
private final Class<T> clazz;
private final long value;
public Id(Class<T> clazz, long value) {
this.clazz = clazz;
this.value = value;
}
}
If Gson encounters an object of type Id during deserialization, it will throw an
exception. The easiest way to solve this problem will be to add a (public or private) no-args
constructor as follows:
private Id() {
this(Object.class, 0L);
}
However, let us assume that the developer does not have access to the source-code of the
Id class, or does not want to define a no-args constructor for it. The developer can
solve this problem by defining an InstanceCreator for Id:
class IdInstanceCreator implements InstanceCreator<Id> {
public Id createInstance(Type type) {
return new Id(Object.class, 0L);
}
}
Note that it does not matter what the fields of the created instance contain since Gson will
overwrite them with the deserialized values specified in JSON. You should also ensure that a
new object is returned, not a common object since its fields will be overwritten. The
developer will need to register IdInstanceCreator with Gson as follows:
Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdInstanceCreator()).create();
GsonBuilder#registerTypeAdapter(Type, Object)
| Modifier and Type | Method and Description |
|---|---|
| public T | Returns: a default object instance of type T.the parameterized T represented as a type)Type.Gson invokes this call-back method during deserialization to create an instance of the specified type. |
| createInstance | back to summary |
|---|---|
| public T createInstance(Type type) Gson invokes this call-back method during deserialization to create an instance of the
specified type. The fields of the returned instance are overwritten with the data present in
the JSON. Since the prior contents of the object are destroyed and overwritten, do not return
an instance that is useful elsewhere. In particular, do not return a common instance, always
use | |