在项目中同样遇到了对json字符串进行反序列化时,遇到了多态情况下,无法找到对应类,所以写这篇文章来mark一下
首先抛出原始代码,再给上解决方案~
原始代码:
原始json串:
{"type":"int","specs":{"min":"1","max":"12","unit":"aw","unitName":"饱和度","step":"1"}}
TslDataType对象,Type 为内部枚举类,TslSpecs为接口,对应枚举类类型的各个实现类
TslDataType:构造方法中type是通过tslSpecs的方法来给赋值的
import com.lbs.iot.beans.tsl.specs.TslSpecs;
public class TslDataType {
private final Type type;
private final TslSpecs specs;
public TslDataType(TslSpecs specs) {
this.type = specs.getType();
this.specs = specs;
}
public Type getType() {
return type;
}
public TslSpecs getSpecs() {
return specs;
}
public enum Type {
INT("int"),
TEXT("text"),
DATE("date"),
BOOL("bool"),
ENUM("enum"),
ARRAY("array"),
FLOAT("float"),
STRUCT("struct"),

"本文介绍了在Java中使用Gson反序列化时遇到接口类型无法实例化的问题,以及如何通过自定义JsonDeserializer解决。在多态场景下,由于无法确定具体实现类,导致Gson报错。解决方案是创建一个自定义反序列化器,根据json中的特定字段(如"type")注册各接口实现类,然后在反序列化时根据该字段找到对应的类进行实例化。"

2408

被折叠的 条评论
为什么被折叠?



