AndBase开发框架  1.6
 全部  命名空间 文件 函数 变量 枚举值 
Public 成员函数 | 所有成员列表
com.google.gson.JsonDeserializer< T >接口 参考
类 com.google.gson.JsonDeserializer< T > 继承关系图:
com.google.gson.DefaultDateTypeAdapter

Public 成员函数

deserialize (JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
 

详细描述

Interface representing a custom deserializer for Json. You should write a custom deserializer, if you are not happy with the default deserialization done by Gson. You will also need to register this deserializer through 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 {
    return new Id((Class)typeOfT, id.getValue());
  }

You will also need to register

IdDeserializer

with Gson as follows:

Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdDeserializer()).create();

New applications should prefer TypeAdapter, whose streaming API is more efficient than this interface's tree API.

作者
Inderjeet Singh
Joel Leitch
参数
<T>type for which the deserializer is being registered. It is possible that a deserializer may be asked to deserialize a specific generic type of the T.

成员函数说明

T com.google.gson.JsonDeserializer< 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 JsonDeserializationContext#deserialize(JsonElement, Type) method to create objects for any non-trivial field of the returned object. However, you should never invoke it on the the same type passing

json

since that will cause an infinite loop (Gson will call your call-back method again).

参数
jsonThe Json data being deserialized
typeOfTThe type of the Object to deserialize to
返回
a deserialized object of the specified type typeOfT which is a subclass of
T
异常
JsonParseExceptionif json is not in the expected format of
typeofT

com.google.gson.DefaultDateTypeAdapter 内被实现.


该接口的文档由以下文件生成: