I have the following code as example of what I am trying to achieve:
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";
}
The following code result in this exception:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to ParseJson$A
at ParseJson.main(ParseJson.java:19)
So the question is: How to get the correct instances inside of a generic HashMap being serialized and deserialized by Gson?