Deserializing Generic Types from a ClassLouder class with GSON

210 Views Asked by At

I´m trying to parse a JSON file using GSON, the problem is that I´m using a Class that it was previously loaded by ClassLoader.

File root = new File("./build/classes");
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });

Class<?> loadedClass = Class.forName("events.Source", true,classLoader);


// JSON --> Java "Get the actual type"
Type listType = new TypeToken<ArrayList<loadedClass>>() {}.getType(); 

Gson gson = new Gson();

ArrayList<loadedClass> resourcesList = gson.fromJson(jsonString, listType);

That returns a com.google.gson.internal.LinkedTreeMap not a List of my own loadedClass. Any help?

1

There are 1 best solutions below

0
On BEST ANSWER

see here a default implementation of ParametrizedType:

http://www.java2s.com/Code/Java/Generics/DefaultimplementationoflinkjavalangreflectParameterizedType.htm

properly prepared, such a type could be used to represent a generic type, which may work with GSON. Without having tested it, your code might then look like this:

File root = new File("./build/classes");
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] {
   root.toURI().toURL()
});
Class<?> loadedClass = Class.forName("events.Source", true,classLoader);

// JSON --> Java "Create the actual type"
Type listType = new DefaultParameterizedType(ArrayList.class, loadedClass);

Gson gson = new Gson();
ArrayList<loadedClass> resourcesList = gson.fromJson(jsonString, listType);