【Java】Gson含抽象类的反序列化

Gson含抽象类的反序列化

场景描述:

反序列化A类的时候,这个类里面有一个抽象类属性B,B的实现类C里面又有一个抽象类属性D,D的实现类是E

实体类准备

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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 + '\'' +
'}';
}
}

反序列化适配器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
}
}
}

反序列化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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();
}
}
}