Cheetah
Cheetah

Reputation: 14399

Deserialize to type at runtime

I am trying to use TypeAdapterFactory to serialize and deserialize some customer objects. I would like to serialize all the objects to a particular type at runtime.

So given a String classpath and a JsonObject object I would like to deserialize the object to an instance of 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
            {
            }
        };
}

How would I go about this?

Upvotes: 3

Views: 955

Answers (1)

PomPom
PomPom

Reputation: 1478

You can try something like this (code wont compile, you need to catch exceptions). Maybe there is a better syntax for THIS too.

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 {
      }
    };
  }
}

Upvotes: 1

Related Questions