Genson deserialize a list of given types

450 Views Asked by At

I'm writing a help function. getList will get serialized data from somewhere, and deserialize it.

getList always returns a List. Users will specify the type of the elements. The expected usage is like this:

List<Asset> l1 = getList("Asset"); //warning Unchecked assignment is fine
List<Store> l2 = getList("Store");
//or 
List<Asset> l1 = getList(Asset.class);
List<Store> l2 = getList(Store.class);
//or 
List<Asset> l1 = getList<Asset>();
List<Store> l2 = getList<Store>();

How would I fix the following implementation? It doesn't compile because className is a variable while List<> expects a class.

public static List getList(String className)
{
    Genson genson = new Genson();
    String data = ...
    List l= genson.deserialize(data, List<className>);
                                     ~~~~~~~~~~~~~~~
    return l;
}
1

There are 1 best solutions below

1
On

There is a getting started guide for geson at http://genson.io/GettingStarted. This has the following example for generic types:

List<Person> persons = genson.deserialize(json, new GenericType<List<Person>>(){});

If you want to pass the type of the list elements to the method, you can introduce a type parameter:

public static <T> List<T> getList(String json, Class<T> clazz) {
    Genson genson = new Genson();
    List<T> list = genson.deserialize(json, new GenericType<List<T>>(){});
    return list;
}

An example for using the method would then look like this:

public static void main(String[] args) {
    List<String> stringList = getList("[ \"element1\", \"element2\" ]", String.class);
    System.out.println(stringList);

    List<Integer> integerList = getList("[ 1, 2, 3 ]", Integer.class);
    System.out.println(integerList);
}

This will produce the following output:

[element1, element2]
[1, 2, 3]