Java 抽象类的自定义gson序列化
也许我走错了方向,但我有一个元素列表,我想读 我有一个抽象基类,我们称它为Java 抽象类的自定义gson序列化,java,serialization,gson,Java,Serialization,Gson,也许我走错了方向,但我有一个元素列表,我想读 我有一个抽象基类,我们称它为Person: public abstract class Person { public int id; public String name; } 现在我有两种可能的实现: public class Hunter implements Person { public int skill; // and some more stuff } public class Zombie imp
Person
:
public abstract class Person {
public int id;
public String name;
}
现在我有两种可能的实现:
public class Hunter implements Person {
public int skill;
// and some more stuff
}
public class Zombie implements Person {
public int uglyness;
// and some more stuff
}
现在我有一个JSON示例:
[
{"id":1, "type":"zombie", "name":"Ugly Tom", "uglyness":42},
{"id":2, "type":"hunter", "name":"Shoot in leg Joe", "skill":0}
]
如何将此JSON读取为列表
我在使用TypeAdapterFactory
玩了一会儿,并尝试使用一个名为的类,因为我的实际结构比上面有趣的示例复杂一些
最后,我想通过此调用委托序列化:
return gson.getDelegateAdapter(this, resultType);
但是,我不知道如何在运行时创建此调用所需的TypeToken
。有什么想法吗
如何将此JSON读取为列表
一种可能是创建一个像工厂一样工作的自定义反序列化器
第一步是定义这个反序列化程序
class PersonJsonDeserializer implements JsonDeserializer<Person> {
@Override
public Person deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String type = json.getAsJsonObject().get("type").getAsString();
switch(type) {
case "zombie":
return context.deserialize(json, Zombie.class);
case "hunter":
return context.deserialize(json, Hunter.class);
default:
throw new IllegalArgumentException("Neither zombie or hunter");
}
}
}
如果类型的值已对应于类名,则可能还需要使用class.forName
:
class PersonJsonDeserializer implements JsonDeserializer<Person> {
@Override
public Person deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String className = json.getAsJsonObject().get("type").getAsString();
className = Character.toUpperCase(className.charAt(0)) + className.substring(1);
try {
return context.deserialize(json, Class.forName(className));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
类PersonJsonDeserializer实现JsonDeserializer{
@凌驾
公共人物反序列化(JsonElement json,类型typeOfT,JsonDeserializationContext)抛出JsonParseException{
字符串className=json.getAsJsonObject().get(“type”).getAsString();
className=Character.toUpperCase(className.charAt(0))+className.substring(1);
试一试{
反序列化(json,Class.forName(className));
}catch(classnotfounde异常){
抛出新的运行时异常(e);
}
}
}
这个问题看起来很相似
Zombie{id=1; name=Ugly Tom; uglyness=42}
Hunter{id=2; name=Shoot in leg Joe; skill=0}
class PersonJsonDeserializer implements JsonDeserializer<Person> {
@Override
public Person deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String className = json.getAsJsonObject().get("type").getAsString();
className = Character.toUpperCase(className.charAt(0)) + className.substring(1);
try {
return context.deserialize(json, Class.forName(className));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}