4

Json 解析丢失子类信息

 10 months ago
source link: https://www.v2ex.com/t/954727
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Java

Json 解析丢失子类信息

  nnegier · 2 小时 36 分钟前 · 710 次点击

子类们的共同父类:BasePlugin

生成 Json ,子类信息都可以很好的输出

String json = new Gson().toJson(list);

但是,如果从 Json 中解析泛型类,它的子类的信息就获取不到,无法类型强转

Type type = new TypeToken<List<BasePlugin>>() {
}.getType();
return new Gson().fromJson(json, type);

这个有可能解决吗?

5 条回复    2023-07-07 10:42:33 +08:00
koloonps

koloonps      1 小时 40 分钟前

new ObjectMapper().readValue("", new TypeReference<Object>() {
@Override
public Type getType() {
return super.getType();
}
})
AoEiuV020JP

AoEiuV020JP      40 分钟前

讲道理,仔细想想, 如果可以从父类泛型这样得到子类的属性,那人家直接内置一个,
Type type = new TypeToken<List<Object>>() {
}.getType();
压根都不需要暴露出 TypeToken 了,

这问题一定是无解的, 具体类型必须有个渠道提供给 json 框架,
加个 if else 判断然后 new 不同的 TypeToken 吧,
或者这个 type 改从外部传入,
MozzieW

MozzieW      32 分钟前

楼上的回复解决的范型 List ,OP 要的是范型 List+子类。
实践上,应该不能这么操作。解决范型 List 反序列话时候,我们是通过带入一个 Type 指定类型,解决类型丢失问题。而 OP 场景下,还多了一个子类型丢失问题。
最简单的方法,不要用子类,一个类接收全部参数,通过 type 区分行为,后续通过设计模式、switch 、if 代码 解决代码复用、逻辑问题。
其他方法:JSON 序列化时引入子类 type ,反序列化时先转为 map ,再根据 type 的值转为子类。
xiangyuecn

xiangyuecn      6 分钟前

你实例化一个父类的实例,怎么可能会包含子类才有的属性🐶

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK