GsonBuilder#registerTypeAdapter(Type, Object).
Let us look at example where defining a deserializer will be useful. The Id class
defined below has two fields: clazz and value.
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;
}
public long getValue() {
return value;
}
}
The default deserialization of Id(com.foo.MyObject.class, 20L) will require the JSON
string to be {"clazz":"com.foo.MyObject","value":20}. Suppose, you already know the
type of the field that the Id will be deserialized into, and hence just want to
deserialize it from a JSON string 20. You can achieve that by writing a custom
deserializer:
class IdDeserializer implements JsonDeserializer<Id> {
public Id deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
long idValue = json.getAsJsonPrimitive().getAsLong();
return new Id((Class) typeOfT, idValue);
}
}
You will also need to register IdDeserializer with Gson as follows:
Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdDeserializer()).create();
Deserializers should be stateless and thread-safe, otherwise the thread-safety guarantees of
Gson might not apply.
New applications should prefer TypeAdapter, whose streaming API is more efficient than
this interface's tree API.
| Modifier and Type | Method and Description |
|---|---|
| public T | Returns: a deserialized object of the specified type typeOfT which is a subclass ofTThe Json data being deserialized json, Type The type of the Object to deserialize to typeOfT, JsonDeserializationContext context)Gson invokes this call-back method during deserialization when it encounters a field of the specified type. |
| deserialize | back to summary |
|---|---|
| public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException Gson invokes this call-back method during deserialization when it encounters a field of the specified type. In the implementation of this call-back method, you should consider invoking
| |