是否有可能在gson中编写一个json反序列化器,它首先调用默认行为,然后我可以对我的对象进行一些后期处理.例如:
public class FooDeserializer implements JsonDeserializer<Foo> {
public Foo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Foo foo = context.deserialize(json, typeOfT);//Standard deserialization call?????
foo.doSomething();
return foo();
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用gson 1.3(我不能使用任何其他版本,因为我只能使用公司存储库中的版本)
谢谢
小智 3
您可以通过为要反序列化的对象(例如 CustomClass.class)实现自定义 TypeAdapterFactory 来实现此目的,如下所示。
public class CustomTypeAdapterFactory implements TypeAdapterFactory {
public final TypeAdapter create(Gson gson, TypeToken type) {
return new TypeAdapter() {
@Override
public void write(JsonWriter out, Object value) throws IOException {
JsonElement tree = delegate.toJsonTree(value);
//add code for writing object
}
@Override
public Object read(JsonReader in) throws IOException {
JsonElement tree = elementAdapter.read(in);
//Add code for reading object
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
然后用Gson将其注册为
Gson gson = new GsonBuilder().registerTypeAdapter(CustomClass.class,new CustomTypeAdapterFactory()).create();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5661 次 |
最近记录: |