什么叫做自省
FastJson如何实现反序列时自省
https://en.wikipedia.org/wiki/Type_introspection
最近在使用到fastjson解析时遇到一个问题,我的类某个属性有多个子类,解析时如何识别到具体的子类呢,查阅了一些博客之后,发现fastjson有自省特性
只需要在被解析的JSON对象中添加@type:'FULL Class Path'即可实现指定类型解析
代码参考如下
public class School{
private Teacher teacher;
public School(Teacher teacher) {
this.teacher = teacher;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
public class EnglishTeacher implements Teacher{
public String myName() {
return "英语老师";
}
}
public class ChineseTeacher implements Teacher{
public String myName() {
return "语文老师";
}
}
可以看到Teacher类有有个子类,如果要指定要解析成哪个子类,只需要在子json中添加@type属性即可
public class FastJsonTest {
public static void main(String[] args) {
School school = new School(new EnglishTeacher());
System.out.println(JSON.toJSONString(school,SerializerFeature.WriteClassName));
School schoolreverse = JSON.parseObject("{\"@type\":\"fastjsontest.School\",\"teacher\":{\"@type\":\"fastjsontest.EnglishTeacher\"}}",School.class);
System.out.println(schoolreverse.getTeacher().myName());
}
}