this is pojo
class Mother {
//..
}
@Data
@AllArgsConstructor
class Son extends Mother {
private int age;
}
@Data
@AllArgsConstructor
class Daughter extends Mother {
private int age;
}
this is main
public static void main(String[] args) {
List<Son> sons = new ArrayList<>();
sons.add(new Son(12));
sons.add(new Son(13));
List<Daughter> daughters = new ArrayList<>();
daughters.add(new Daughter(5));
daughters.add(new Daughter(6));
Map<String,List<? extends Mother>> map = new HashMap<>();
map.put("ex-husband",sons);
map.put("husband",daughters);
Gson gson = new Gson();
String json = gson.toJson(map);
System.out.println(json);
//ok
Gson gson1 = new Gson();
Type type = new TypeToken<Map<String,List<? extends Mother>>>() {}.getType();
Map<String,List<? extends Mother>> map1 = gson1.fromJson(json,type);
List<Son> sons1 = (List<Son>) map1.get("ex-husband");
System.out.println(sons1.get(0).getAge());
//error
}
this is error
java.lang.ClassCastException: Mother cannot be cast to Son
This is the json after formatting
{
"ex-husband": [
{
"age": 12
},
{
"age": 13
}
],
"husband": [
{
"age": 5
},
{
"age": 6
}
]
}
It is structured around the following. Map<String, List<? extends Mother>>
gson can be serialized to json normally, but in turn it does not recognize the specific Son and Daughter types, and therefore cannot read the values of specific properties
My expectation is that it is possible to read subclass attributes after deserialization, but it reports an error, guys, how can this be corrected, is there a good way to do it?
ok, i got it,haha
result: