反序列化以在运行时键入

时间:2013-07-28 15:05:38

标签: java serialization gson

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

所以给定String classpathJsonObject 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
            {
            }
        };
}

我该怎么做?

1 个答案:

答案 0 :(得分: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 {
      }
    };
  }
}