这是一个很好的问题,因为它隔离了一些应该很容易但实际上需要大量代码的东西。
首先,编写一个摘要TypeAdapterFactory
,为您提供钩子以修改传出数据。本示例在Gson 2.2中使用了一个新的API,该API getDelegateAdapter()
允许您查找Gson默认情况下将使用的适配器。如果您只想调整标准行为,则委托适配器非常方便。与完全自定义类型的适配器不同,在添加和删除字段时,它们将自动保持最新状态。
public abstract class CustomizedTypeAdapterFactory<C>
implements TypeAdapterFactory {
private final Class<C> customizedClass;
public CustomizedTypeAdapterFactory(Class<C> customizedClass) {
this.customizedClass = customizedClass;
}
@SuppressWarnings("unchecked") // we use a runtime check to guarantee that 'C' and 'T' are equal
public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
return type.getRawType() == customizedClass
? (TypeAdapter<T>) customizeMyClassAdapter(gson, (TypeToken<C>) type)
: null;
}
private TypeAdapter<C> customizeMyClassAdapter(Gson gson, TypeToken<C> type) {
final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
return new TypeAdapter<C>() {
@Override public void write(JsonWriter out, C value) throws IOException {
JsonElement tree = delegate.toJsonTree(value);
beforeWrite(value, tree);
elementAdapter.write(out, tree);
}
@Override public C read(JsonReader in) throws IOException {
JsonElement tree = elementAdapter.read(in);
afterRead(tree);
return delegate.fromJsonTree(tree);
}
};
}
/**
* Override this to muck with {@code toSerialize} before it is written to
* the outgoing JSON stream.
*/
protected void beforeWrite(C source, JsonElement toSerialize) {
}
/**
* Override this to muck with {@code deserialized} before it parsed into
* the application type.
*/
protected void afterRead(JsonElement deserialized) {
}
}
上面的类使用默认的序列化来获取JSON树(由表示JsonElement
),然后调用hook方法beforeWrite()
以允许子类自定义该树。与相同的反序列化afterRead()
。
接下来,我们将其子类化为特定MyClass
示例。为了说明这一点,我将在序列化时向地图添加一个名为“ size”的综合属性。为了对称起见,我会在反序列化时将其删除。实际上,这可以是任何定制。
private class MyClassTypeAdapterFactory extends CustomizedTypeAdapterFactory<MyClass> {
private MyClassTypeAdapterFactory() {
super(MyClass.class);
}
@Override protected void beforeWrite(MyClass source, JsonElement toSerialize) {
JsonObject custom = toSerialize.getAsJsonObject().get("custom").getAsJsonObject();
custom.add("size", new JsonPrimitive(custom.entrySet().size()));
}
@Override protected void afterRead(JsonElement deserialized) {
JsonObject custom = deserialized.getAsJsonObject().get("custom").getAsJsonObject();
custom.remove("size");
}
}
最后,通过创建Gson
使用新类型适配器的自定义实例将它们放在一起:
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new MyClassTypeAdapterFactory())
.create();
Gson的新TypeAdapter和TypeAdapterFactory类型非常强大,但它们也很抽象,需要练习才能有效使用。希望您发现此示例有用!