【发布时间】:2022-01-28 13:21:57
【问题描述】:
我有 4 个不同的 Hashmap,它们的值具有不同的类类型。
(Hashmap
其中每一个在资源文件夹中都有一个相应的目录,其中包含一组 Json 文件。 我想将目录中的所有 Json 文件反序列化为正确的类类型,并将它们存储在作为参数输入的 HashMap 中。
Gson 需要输入我写过#OBJECTCLASS# 的类类型来创建对象。如何从作为方法参数输入的 HashMap 中获取?
//load a hashmap with the objects saved in its resource file
public static void loadObjsFromDirectory(HashMap<String, Object> map, String directoryPath) {
File[] files = new File(directoryPath).listFiles();
//null safety
if (files == null) {
System.out.println(filePath + " is empty");
return;
}
Gson gsonDeserializer = new Gson();
//deserialize each json file and put the created object in its map
for (File file : files) {
//make sure the Json file is parsed correctly
try {
Object object = gsonDeserializer.fromJson(String.valueOf(file), #OBJECTCLASS#);
map.put(file.getName(), object);
System.out.println(file.getName() + " is loaded");
} catch (JsonParseException e){
System.out.println(file.getName() + "is incorrectly parsed");
}
}
}
例如
public static void main(String[] args) throws Exception {
HashMap<String, Class1> map1 = new HashMap<>();
HashMap<String, Class2> map2 = new HashMap<>();
Utils.loadObjsFromDirectory(map1, "directoryPath1");
Utils.loadObjsFromDirectory(map2, "directoryPath2");
}
应该将 directoryPath1 中的所有文件创建为 Class1 对象,并将 directoryPath2 中的所有文件创建为 Class2 对象。
【问题讨论】:
-
您可以将您的方法更改为
public static void loadObjsFromDirectory(HashMap<String, Object> map, String directoryPath, Class klass)并以Utils.loadObjsFromDirectory(map1, "directoryPath1", Class1.class);或地图值中的任何类的方式调用它
标签: java hashmap gson deserialization