Maurício Giordano
Maurício Giordano

Reputation: 3276

Get Type of ParameterizedType from generic

I cannot understand fully how reflect works, so I'm having some trouble trying to register a custom type adapter for my GsonBuilder.

I need to register a type adapter for a List<Something> type.

This is a working code:

    gsonBuilder.registerTypeAdapter(
            new TypeToken<List<MyClass>>() { }.getType(), new ListDeserializer(MyClass.class)
    );

The thing is that I have a lot of classes to register my type adapter, and I have a ListDeserializer and SingleDeserializer adapters.

I'm trying to go generic so I just call a function, pass my GsonBuilder and class, and there you go.

Here is my try:

private static <T> void registerTypeAdapter(GsonBuilder gsonBuilder, T clazz) {
    gsonBuilder.registerTypeAdapter(clazz.getClass(), new SingleDeserializer(clazz.getClass()));
    gsonBuilder.registerTypeAdapter(
            new TypeToken<List<T>>() {
            }.getType(), new ListDeserializer(clazz.getClass())
    );
}

It doesn't work for my ListDeserializer. My guess is that since T is a generic parameterized type of List, it cannot detect it at runtime.

Any suggestions?

Upvotes: 0

Views: 1738

Answers (1)

varren
varren

Reputation: 14731

Yep you can't use new TypeToken<List<T>>() {}.getType() at runtime, because of generics type erasure. List<T> is just List<Object> at runtime. but what you could do is to create ParameterizedType and use something like this:

Type type = ParameterizedTypeImpl.make(List.class, new Type[]{clazz.getClass()}, null);
gsonBuilder.registerTypeAdapter(type, new ListDeserializer(clazz.getClass()) );

But do you really need genericness? You could do

private static void registerTypeAdapter2(GsonBuilder gsonBuilder, Class<?> clazz) {
    gsonBuilder.registerTypeAdapter(clazz, new SingleDeserializer());
    Type type = ParameterizedTypeImpl.make(List.class, new Type[]{clazz}, null);
    gsonBuilder.registerTypeAdapter(type, new ListDeserializer());
}

Here is demo:

import com.google.gson.*;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {
        GsonBuilder gb = new GsonBuilder();
        registerTypeAdapter(gb, MyClass.class);

        Gson gson = gb.create();
        List data = new ArrayList<>();
        data.add(new MyClass("Bob"));
        data.add(new MyClass("Alice"));

        String listString = gson.toJson(data);
        String soloString = gson.toJson(new MyClass("Test"));

        Object resultList = gson.fromJson(listString, new TypeToken<List<MyClass>>() {}.getType());
        Object resultSolo = gson.fromJson(soloString, MyClass.class);

        System.out.println("RESULT:");
        System.out.println("FROM " + listString +" TO "+ resultList);
        System.out.println("FROM " + soloString +" TO "+ resultSolo);

    }

    private static void registerTypeAdapter(GsonBuilder gsonBuilder, Class<?> clazz) {
        gsonBuilder.registerTypeAdapter(clazz, new SingleDeserializer());
        Type type = ParameterizedTypeImpl.make(List.class, new Type[]{clazz}, null);
        gsonBuilder.registerTypeAdapter(type, new ListDeserializer());
    }

    private static class ListDeserializer implements JsonDeserializer {
        private static Gson gson = new Gson();

        @Override
        public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            System.out.println("Used ListDeserializer:  Type " + typeOfT);

            Type t = (typeOfT instanceof ParameterizedType) ?
                    ((ParameterizedType) typeOfT).getActualTypeArguments()[0] :
                    Object.class;

            Type type = ParameterizedTypeImpl.make(List.class, new Type[]{t}, null);
            List list = gson.fromJson(json, type);
            return list;
        }
    }

    private static class SingleDeserializer implements JsonDeserializer {
        private static Gson gson = new Gson();

        @Override
        public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            System.out.println("Used SingleDeserializer:  Type " + typeOfT);
            return gson.fromJson(json, typeOfT);
        }
    }

    public static class MyClass {
        @SerializedName("name")
        private String name;

        public MyClass(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "MyClass{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
}

Upvotes: 2

Related Questions