3

我正在尝试使用TypeAdapterFactory序列化和反序列化一些客户对象。我想在运行时将所有对象序列化为特定类型。

所以给定 aString classpath和 aJsonObject object我想将对象反序列化为Class.forName(classpath).

public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> tokenType)
{
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, tokenType);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

    return new TypeAdapter<T>()
        {
            @Override
            public T read(JsonReader reader) throws IOException
            {
                Class<?> clazz = Class.forName(classpath);
                JsonObject jsonObject = elementAdapter.read(reader).getAsJsonObject();

                // Here I want to return an instance of clazz
            }

            @Override
            public void write(JsonWriter writer, T value) throws IOException
            {
            }
        };
}

我该怎么办?

4

1 回答 1

1

您可以尝试这样的事情(代码不会编译,您需要捕获异常)。也许也有更好的语法THIS

final class MyClass implements TypeAdapterFactory {
  @Override
  public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> tokenType) {
    final MyClass THIS = this;

    return new TypeAdapter<T>() {
      @Override
      public T read(JsonReader reader) throws IOException {
        Class<?> clazz = Class.forName(classpath);

        TypeToken<T> token = (TypeToken<T>) TypeToken.get(clazz);
        TypeAdapter<T> adapter = gson.getDelegateAdapter(THIS, token);
        JsonElement tree = gson.getAdapter(JsonElement.class).read(reader);
        T out = adapter.fromJsonTree(tree);

        return out;
      }

      @Override
      public void write(JsonWriter writer, T value) throws IOException {
      }
    };
  }
}
于 2013-07-29T13:23:29.643 回答