使用 GSON 从 ClassLouder class 反序列化通用类型
Deserializing Generic Types from a ClassLouder class with GSON
我正在尝试使用 GSON 解析 JSON 文件,问题是我使用的 Class 之前是由 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);
那个returns一个com.google.gson.internal.LinkedTreeMap不是一个我自己加载的列表Class。有帮助吗?
在此处查看 ParametrizedType 的默认实现:
准备得当,这样的类型可以用来表示通用类型,它可以与 GSON 一起使用。未经测试,您的代码可能如下所示:
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);
我正在尝试使用 GSON 解析 JSON 文件,问题是我使用的 Class 之前是由 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);
那个returns一个com.google.gson.internal.LinkedTreeMap不是一个我自己加载的列表Class。有帮助吗?
在此处查看 ParametrizedType 的默认实现:
准备得当,这样的类型可以用来表示通用类型,它可以与 GSON 一起使用。未经测试,您的代码可能如下所示:
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);