class Human {
String name;
}
class Student extends Human {
String college;
}
class Worker extends Human {
String workPlace;
}
假设我想使用GSON序列化它。
是否可以为每个序列化"type" : "student"
实例添加一对Student
(就像type
是该类的字段一样)?同样,为每个"type" : "worker"
实例添加Worker
相关问题涉及此类JSONS的反序列化: Deserialize recursive polymorphic class in GSON
答案 0 :(得分:0)
你可以通过gson自定义JsonSerializer这样做
public class HumanSerializer implements JsonSerializer<Human> {
@Override
public JsonElement serialize(final Human human, final Type type, final JsonSerializationContext context) {
final JsonObject json = new JsonObject();
if(human instanceof Human)
json.addProperty("type", "Human");
if(human instanceof Worker)
json.addProperty("type", "Worker");
if(human instanceof Student)
json.addProperty("type", "Student");
json.addProperty("name", human.getName());
return json;
}
}
最后你必须注册你的课程然后序列化
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Human.class,new HumanSerializer());
gsonBuilder.registerTypeAdapter(Worker.class,new HumanSerializer());
gsonBuilder.registerTypeAdapter(Student.class,new HumanSerializer());
final Gson gson = gsonBuilder.create();
输出
gson.toJson(new Worker("adam", "workplace"));
gson.toJson(new Human("Jhon"));
{"type":"Worker","name":"adam"}
{"type":"Human","name":"Jhon"}