是否可以在 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();
}
}
我正在使用 gson 1.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
}
};
}
}
然后用 Gson 注册为
Gson gson = new GsonBuilder().registerTypeAdapter(CustomClass.class,new CustomTypeAdapterFactory()).create();
https://stackoverflow.com/questions/3932671/