0

I want to use the Google Gson library to (de)serialize a parameterized type that has a parameterized member field.

The class looks like this:

public class Foo<T>{
    List<T> bar;
}

How do I go about this?

I tried using a TypeToken like so:

Type type = new TypeToken<Foo<String>>() {}.getType();
gson.fromJson<Foo<String>>(json, type);

This throws an IllegalStateException

1 Answers1

0

This post might help you: Deserializing Generic Types with GSON

TLDR, I tried it out for your class and you can use this code to deserialize Foo:

GsonBuilder gson = new GsonBuilder();
String json = "{\"bar\":[\"thing1\",\"thing2\"]}";
Foo deserFoo = gson.create().fromJson(json, Foo.class);
System.out.println(deserFoo.bar);

It outputs [thing1, thing2]

  • Thanks, reading your code made me realize the error I was getting was due to a syntax error in my json test string. There was no problem with the serialization after all. :facepalm: – Knut Zuidema Jan 11 '18 at 01:44