John Long
John Long

Reputation: 133

GSON deserialize with passed generics

I am working a simple facade for JSON mapping libraries. For my default implementation I am using GSON but have run into an issue. I've defined a class similar to this:

    public class QueryResult<T> {

        private List<T> results;
        private String nextOffset;

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

        public void setResults(List<T> results) { this.results = results; }

        public String getNextOffset() { return nextOffset; }

        public void setNextOffset(String nextOffset) { this.nextOffset = nextOffset; }
    }

and would like to do something like this with it:

    public <T> QueryResult<T> fromJsonQuery(String string, Class<T> clazz) {
        Type type = new TypeToken<QueryResult<T>>() {}.getType();
        return gson.fromJson(string, type);
    }

However, whenever I call this method I get an error:

    QueryResult<Foo> qr = mapper.fromJsonQuery(json, Foo.class);
    for (Foo foo : qr.getResults()) {
        System.out.println(foo.toString());
    }

    java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to example.Foo

Any help would be greatly appreciated. Thanks.

Upvotes: 4

Views: 304

Answers (1)

John Long
John Long

Reputation: 133

I've come up with a solution that will work for me. Basically, I define inner classes that extend QueryResult for the various types I need. In my facade I defined this method:

    public <T> T fromJson(String string, Class<T> clazz) {
        return gson.fromJson(string, clazz);
    }

Then I can do the following and it works:

    public class Main {

        class FooQuery extends QueryResult<Foo> {}

        public static void main(String[] args) {
            Mapper mapper = new GsonMapper();
            String json = args[0];

            QueryResult<Foo> qr = mapper.fromJson(json, FooQuery.class);

            for (Foo foo : qr.getResults()) {
                System.out.println(foo.toString());
            }
    }

Upvotes: 1

Related Questions