gson:将函数结果添加到由toJson()创建的对象

Joh*_*pel 5 json gson

gson是一个很棒的序列化/反序列化工具.通过使用toJson函数获取任意对象的JSON表示非常简单.

现在我想将我的对象的数据发送到浏览器以在javascript/jQuery中使用.因此,我需要一个额外的JSON元素来定义对象的dom类,该对象在我的对象中被编码为动态/无成员函数

public String buildDomClass()
Run Code Online (Sandbox Code Playgroud)

如何将此字符串添加到由toJson函数创建的String中?

有任何想法吗?

非常感谢

Pom*_*Pom 3

一个简单的方法是将 aTypeAdapterFactory和 an 接口结合起来。

首先是您的方法的接口:

  public interface MyInterface {
    public String buildDomClass();
  }
Run Code Online (Sandbox Code Playgroud)

然后是工厂:

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);
      }
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

很容易理解,如果你想要序列化的对象实现了接口,你可以委托序列化,然后添加一个额外的属性来保存你的 DOM。

如果你不知道,你可以像这样注册一个工厂

Gson gson = new GsonBuilder().registerTypeAdapterFactory(new MyAdapter()).create();
Run Code Online (Sandbox Code Playgroud)