我试图使用Google的Gson库在Java中序列化和反序列化一个HashMap。我希望序列化这里所示的hashmap,将其保存到一个文件中,然后在以后的阶段从一个文件中读取并反序列化它。
HashMap如下所示
public static HashMap<Integer,HashMap <Integer, Type5Val>> type5Model = new HashMap<Integer, HashMap<Integer, Type5Val>>();
反序列化类的反序列化逻辑,以及我目前基于Web上找到的示例实现的对象类。IS:
public class Type5Val implements Serializable,JsonDeserializer<Type5Val>{
public int modelLogLines;
public int modelTime;
@Override
public Type5Val deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
final JsonObject jsonObject = jsonElement.getAsJsonObject();
System.out.println("Print JSON Object" + jsonObject.getAsString());
final int t_modelLogLines = jsonObject.get("modelLogLines").getAsInt();
final int t_modelTime = jsonObject.get("modelTime").getAsInt();
//Populating
Type5Val val = new Type5Val();
val.modelLogLines = t_modelLogLines;
val.modelTime = t_modelTime;
return val;
}
}
下面是在test函数中调用的序列化和反序列化代码。测试函数序列化上面HashMap的一个对象,创建一个字符串,然后尝试反序列化它。反序列化当前失败:
//serialization code
public static String dump(){
// Configure Gson
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Type5Val.class, new Type5Val());
Gson g = gsonBuilder.create();
String json = g.toJson(type5Model);
return json;
}
//deserialization code
public static HashMap<Integer, HashMap<Integer,Type5Val>> undump(String json){
// Configure Gson
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Type5Val.class, new Type5Val());
Gson g = gsonBuilder.create();
HashMap<Integer,HashMap <Integer, Type5Val>> newModel = g.fromJson(json, type5Model.getClass());
return newModel;
}
public static void printMap(HashMap<Integer,HashMap<Integer,Type5Val>> modelInput){
Iterator<HashMap<Integer, Type5Val>> it = modelInput.values().iterator();
while(it.hasNext()){
HashMap<Integer,Type5Val> temp = it.next();
Iterator<Type5Val> it2 = temp.values().iterator();
while(it2.hasNext()){
Type5Val temp2 = it2.next();
System.out.println("Time: " + temp2.modelTime + " Lines: " + temp2.modelLogLines);
System.out.println(" Queue Size " + temp2.q.size() + "\n");
}
}
}
public static void testcase(){
System.out.println("Printing Initial Map");
printMap(type5Model);
//serialization
String s = dump();
System.out.println(s);
//deserialization
HashMap<Integer, HashMap<Integer,Type5Val>> newModel = undump(s);
System.out.println("Printing Map After Serialization/Deserialization");
printMap(newModel);
}
Printing Initial Map
Time: 0 Lines: 39600000
Queue Size 0
Time: 0 Lines: 46800000
Queue Size 0
//Json output after serialization
{"1":{"1":{"modelLogLines":39600000,"modelTime":0,"q":[]},"2":{"modelLogLines":46800000,"modelTime":0,"q":[]}}}
Printing Map After Serialization/Deserialization
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.simontuffs.onejar.Boot.run(Boot.java:340)
at com.simontuffs.onejar.Boot.main(Boot.java:166)
Caused by: java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to java.util.HashMap
at violationChecker.type5Convert.printMap(type5Convert.java:207)
at violationChecker.type5Convert.testcase(type5Convert.java:259)
at violationChecker.type5Convert.main(type5Convert.java:294)
... 6 more
在这条线上:
HashMap<Integer,HashMap <Integer, Type5Val>> newModel = g.fromJson(json, type5Model.getClass());
您告诉Gson将字符串
反序列化为Hashmap
。只是一个hashmap
,而不是hashmap
,因为所有关于泛型类型参数的信息都在运行时被删除,并且传递给它的是运行时已知的type5model
类型。这迫使Gson猜测应该在hashmap
中作为键和值的类型,并为值中的内部映射生成LinkedTreemap
而不是hashmap
。
要给Gson提供完整的类型,包括泛型类型参数,必须使用typeToken
。要创建适当的typeToken
,请执行以下操作:
new TypeToken<HashMap<Integer, HashMap<Integer, Type5Val>>>(){}.getType()
但是,如果没有typeToken
,您仍然会在其他地方得到另一个错误,因为Gson不会在没有被告知某些对象应该属于type5val
类的情况下猜测。
ClassCastException:com.google.gson.internal.LinkedTreeMap不能强制转换为java.util.HashMap 提前谢了。
以下代码导致此异常: 所以问题是:如何在GSON序列化和反序列化的泛型HashMap中获得正确的实例?
问题内容: 我使用了很多不可变的集合,并且很好奇如何使用Gson反序列化它们。由于没有人回答,而且我自己找到了解决方案,因此我正在简化问题并提出自己的答案。 我有两个问题: 如何为所有人编写一个作品? 如何全部注册? 问题答案: 更新:有https://github.com/acebaggins/gson- serializers ,其中涵盖了许多番石榴集合: 如何编写适用于所有Immutable
问题内容: 我想编写一个通用函数,使用Gson反序列化通用类型List,下面是代码: 但是这段代码不起作用,我得到一个奇怪的结构,但是没有我的类型列表 当我使用时: 我工作,我得到了! 但是我需要一个通用函数,我该如何解决? 问候rubiktubik 问题答案: 没有将(as )的实际类型传递给您的方法,就无法做到这一点。 但是,如果显式传递它,则可以按如下所示创建for : 也可以看看:
问题内容: 我如何使用gson 2.2.4序列化和反序列化一个简单的枚举? 问题答案: 根据 GsonAPI文档 ,Gson提供了的默认序列化/反序列化,因此基本上,应使用标准和方法(与其他类型一样)对序列化和反序列化。
我需要序列化/反序列化特定枚举: 我有个例外: 我如何通过GSON序列化/反序列化它?