gson 是一个非常棒的序列化/反序列化工具。使用 toJson 函数获取任意对象的 JSON 表示非常简单。
现在我想将我的对象的数据发送到浏览器以在 javascript/jQuery 中使用。因此,我需要一个额外的 JSON 元素来定义在我的对象中编码为动态/无成员函数的对象的 dom 类
public String buildDomClass()
如何将此字符串添加到由 toJson 函数创建的我的字符串中?
有任何想法吗?
非常感谢
一种简单的方法是将 aTypeAdapterFactory
和 interface 结合起来。
首先是您的方法的接口:
public interface MyInterface {
public String buildDomClass();
}
然后是工厂:
final class MyAdapter implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> tokenType) {
final TypeAdapter<T> adapter = gson.getDelegateAdapter(this, tokenType);
return new TypeAdapter<T>() {
@Override
public T read(JsonReader reader) throws IOException {
return adapter.read(reader);
}
@Override
public void write(JsonWriter writer, T value) throws IOException {
JsonElement tree = adapter.toJsonTree(value);
if (value instanceof MyInterface) {
String dom = ((MyInterface) value).buildDomClass();
JsonObject jo = (JsonObject) tree;
jo.addProperty("dom", dom );
}
gson.getAdapter(JsonElement.class).write(writer, tree);
}
};
}
}
很容易理解,如果你想序列化的对象实现了接口,你委托序列化,然后你添加一个额外的属性来保存你的 DOM。
如果你不知道,你注册一个这样的工厂
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new MyAdapter()).create();