0

I have a class with nested subclasses

public class OuterClass {
    class GenericClassHolder<R> {
        @SerializedName("results")
        List<R> results;

        public GenericClassHolder() {}

        public List<R> getResults() {
            return results;
        }
    }

    class ExampleClassA {
        @SerializedName("A")
        int a;

        public ExampleClassA() {}

        public int getA() {return a;}
    }


    class ExampleClassB {
        @SerializedName("B")
        String b;

        public ExampleClassA() {}

        public String getB() {return b;}
    }
}

And I would like to deserialize to different versions of GenericClassHolder in different circumstances. Currently I have

public <T> OuterClass.GenericClassHolder<T> parseJson(final String responseStr, final Class<T> responseClass) throws JsonSyntaxException {
    return Gsons.getInstance().fromJson(responseStr, new TypeToken<OuterClass.GenericClassHolder<T>>() {
    }.getType());
}


String jsonString = "{results:[{A:4}]}";
OuterClass.GenericClassHolder<OuterClass.ExampleClassA> ex = parseApiResponse(jsonString, OuterClass.ExampleClassA.class);

which seems to not break anything but when I get to the following line

System.out.println("I read the string and parsed it! A: " + ex.getResults().get(0).getA());

I get the error

Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to OuterClass$ExampleClassA

How can I achieve the goal of being able to parse to a templated class that contains a list of the parameterized type?

-I am using Java 7.

user3038457
  • 185
  • 2
  • 11
  • 1
    Or [this](http://stackoverflow.com/questions/20773850/gson-typetoken-with-dynamic-arraylist-item-type) but I'm out of votes. – Sotirios Delimanolis Aug 29 '16 at 23:07
  • 1
    The type inferred for `T` exists only at the call site. Your `parseJson` doesn't have access to it. The type of the `TypeToken` is `OuterClass.GenericClassHolder>`, literally, with `T` being a new `Type` representing a `TypeVariable`. – Sotirios Delimanolis Aug 29 '16 at 23:08
  • @shmosel That is very relevant! However, I do not think I have the capability of using Guava AFAIK. – user3038457 Aug 29 '16 at 23:09
  • @SotiriosDelimanolis your link helped me solve the issue more than shmosel's, as I cannot use Guava ( and explained so in the description of the problem). I don't know how to mark it as a duplicate of your link instead of theirs – user3038457 Aug 31 '16 at 00:38
  • 1
    There's not much you can do. I'll switch the duplicates. – Sotirios Delimanolis Aug 31 '16 at 00:41
  • Got it. Thank you so much for all your help :-) – user3038457 Aug 31 '16 at 20:58

0 Answers0