Gson含抽象类的反序列化
2024-10-20 00:26:59
Gson含抽象类的反序列化
场景描述:
反序列化A类的时候,这个类里面有一个抽象类属性B,B的实现类C里面又有一个抽象类属性D,D的实现类是E
实体类准备
public class A implements Serializable {
private B b;
public A(B b) {
this.b = b;
}
@Override
public String toString() {
return "A{" +
"b=" + b +
'}';
}
}
public abstract class B implements Serializable {
protected String name;
public B(){}
public B(String name) {
this.name = name;
}
@Override
public String toString() {
return "B{" +
"name='" + name + '\'' +
'}';
}
}
public class C extends B{
private D d;
public C(String name) {
super(name);
}
public C(String name,D d) {
super(name);
this.d = d;
}
@Override
public String toString() {
return "C{" +
"d=" + d +
'}';
}
}
public abstract class D implements Serializable {
protected String name;
public D(){}
public D(String name) {
this.name = name;
}
@Override
public String toString() {
return "D{" +
"name='" + name + '\'' +
'}';
}
}
public class E extends D{
public E() {
super("this is E");
}
public E(String name, String name1) {
super(name);
this.name = name1;
}
@Override
public String toString() {
return "E{" +
"name='" + name + '\'' +
'}';
}
}
反序列化适配器
public class Adapter<T> implements JsonDeserializer<T> {
private T obj;
@SuppressWarnings("unchecked")
public Adapter(Class<?> clz) {
this.obj = (T) clz;
}
@Override
public T deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
try {
return OK.GsonFactory.gson.fromJson(jsonElement, (Type) Class.forName(((Class) obj).getName()));
} catch (ClassNotFoundException e) {
throw new JsonParseException(e);
}
}
}
反序列化
public class OK {
public static void main(String[] args) {
E e = new E("this is e","this e is filed");
C c = new C("this is c", e);
final A a = new A(c);
final A a1 = GsonFactory.gson.fromJson(new Gson().toJson(a), A.class);
System.out.println(a); // A{b=C{d=E{name='this e is filed'}}}
System.out.println(a1); // A{b=C{d=E{name='this e is filed'}}}
}
public static class GsonFactory {
public static Gson gson;
static {
gson = new GsonBuilder()
// 指定对应抽象类的具体处理类型
.registerTypeAdapter(B.class,new Adapter<C>(C.class))
.registerTypeAdapter(D.class,new Adapter<E>(E.class))
.create();
}
}
}
最新文章
- iOS进阶面试题----Block部分
- linux环境中 对tomcat配置java环境
- IIS配置网站(WebServices),局域网都能访问
- php error_log 详解
- Uva - 11419 - SAM I AM
- log4j.properties 的使用详解
- JS对象引用
- 2017年8月28日 HTML/CSS 语法(待填坑)
- 怎样在一个HTML中嵌入另一个HTML页面(iframe标签用法)
- 微软Azure云计算服务主导全球
- Why the Anaconda command prompt is the first choice in windows?
- topcoder srm 595 div1
- text3
- ln: operation not permitted
- 数据库和struts2的拦截器
- 修改oracle系统参数spfile导致数据库无法启动解决
- C#中通过Lambda表达式为委托传入更多的参数
- Java将List<;T>;集合组装成树(Tree)树结构组装
- 【DP】【P5007】 DDOSvoid 的疑惑
- 内功心法 -- java.util.LinkedList<;E>; (8)