我有以下代码作为我想要实现的目标的示例:
public static void main(String args[]) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("1", new A());
map.put("2", new B());
String json = new Gson().toJson(map);
Type type = new TypeToken<Map<String, Object>>(){}.getType();
map = new Gson().fromJson(json, type);
A a = (A) map.get("1");
B b = (B) map.get("2");
}
static class A {
int inum = 1;
double dnum = 1.0;
String str = "1";
}
static class B {
int inum = 2;
double dnum = 2.0;
String str = "2";
}
以下代码导致此异常:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to ParseJson$A
at ParseJson.main(ParseJson.java:19)
所以问题是: 如何在Gson中序列化和反序列化通用HashMap中的正确实例?
答案 0 :(得分:2)
Object
被反序列化为com.google.gson.internal.LinkedTreeMap
,因此告诉Gson
您想要A
类。
public static void main(String args[]) {
Map<String, Object> map = new HashMap<>();
map.put("1", new A());
String json = new Gson().toJson(map);
Type type = new TypeToken<Map<String, A>>() {
}.getType();
map = new Gson().fromJson(json, type);
A a = (A) map.get("1");
System.out.println(a.str);
}
static class A {
private int num1 = 1;
private double num2 = 2.0;
private String str = "String";
}
希望它有所帮助。
<强>更新强>
基类(在这种情况下为X
)可能是一个解决方案:
public static void main(String args[]) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("1", new A());
map.put("2", new B());
String json = new Gson().toJson(map);
Type type = new TypeToken<Map<String, X>>(){}.getType();
map = new Gson().fromJson(json, type);
X a = (X) map.get("1");
X b = (X) map.get("2");
System.out.println(a.str);
System.out.println(b.str);
}
static class X {
int inum;
double dnum;
String str;
X() {
}
}
static class A extends X {
A() {
inum = 1;
dnum = 1.0;
str = "1";
}
}
static class B extends X {
B() {
inum = 2;
dnum = 2.0;
str = "2";
}
}