曹耘豪的博客

ObjectMapper指定反序列化子类

有以下类结构 A -> B -> C,分别有 a、b、c 字段

1
2
3
4
5
6
7
8
9
10
11
12
13
@Data
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class")
class A implements Serializable {
private String a;
}

@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@class")
class B extends A {
private String b;
}

测试代码,打印出 序列化后的json,并且将json按基类去解析,解析后的类实际上是具体的类。

1
2
3
4
5
6
7
8
9
10
11
12
13
B o = new B();
o.setA("a");
o.setB("b");

ObjectMapper mapper = new ObjectMapper();

String json = mapper.writeValueAsString(o);

System.out.println(json);
A a = mapper.readValue(json, A.class); // 按照基类去解析

System.out.println(a);
System.out.println(mapper.writeValueAsString(a));

输出

1
2
3
{"@class":"com.caoyunhao.test.B","a":"a","b":"b"}
B(super=A(a=a), b=b) // 子类
{"@class":"com.caoyunhao.test.B","a":"a","b":"b"}
   /