使用fastjson反序列化对象
官方地址:https://github.com/alibaba/fastjson
// 见 https://github.com/alibaba/fastjson/wiki/JSONType_seeAlso_cn
@JSONType(seeAlso={Dog.class, Cat.class})
public static class Animal {
}
@JSONType(typeName = "dog")
public static class Dog extends Animal {
public String dogName;
}
@JSONType(typeName = "cat")
public static class Cat extends Animal {
public String catName;
}
// 使用
Dog dog = new Dog();
dog.dogName = "dog1001";
String text = JSON.toJSONString(dog, SerializerFeature.WriteClassName);
Assert.assertEquals("{\"@type\":\"dog\",\"dogName\":\"dog1001\"}", text);
Dog dog2 = (Dog) JSON.parseObject(text, Animal.class);
Assert.assertEquals(dog.dogName, dog2.dogName);
// 使用
Cat cat = new Cat();
cat.catName = "cat2001";
String text = JSON.toJSONString(cat, SerializerFeature.WriteClassName);
Assert.assertEquals("{\"@type\":\"cat\",\"catName\":\"cat2001\"}", text);
Cat cat2 = (Cat) JSON.parseObject(text, Animal.class);
Assert.assertEquals(cat.catName, cat2.catName);
对于抽象类反序列化,需要注意:
- 类要有
无参的构造函数
- 序列化时存储类型信息或者反序列化之前设置类型信息,即
JSON.toJSONString(dog, SerializerFeature.WriteClassName);
或者设置@type
- 需要添加包的白名单以解决
com.alibaba.fastjson.JSONException: autoType is not support. xx.xxxx
错误,添加方式可使用全局配置ParserConfig.getGlobalInstance().addAccept("包路径");
具体可参考文章:解决com.alibaba.fastjson.JSONException: autoType is not support