【发布时间】:2018-10-12 07:21:56
【问题描述】:
我正在使用 GSON 将通用序列化程序应用于抽象 Base 类的所有子类。但是,当给定 Base 类的实际子类时,GSON 不会调用我的序列化程序,除非明确告知使用 Base.class 作为强制转换。这是我所说的一个简单实例。
public interface Base<T>{
String getName();
public List<Object> getChildren();
}
public class Derived1 implements Base<Integer>{
private Integer x = 5;
String getName(){
return "Name: " + x;
}
List<Object> getChildren(){
return Lists.newArrayList(new Derived2(), "Some string");
}
}
public class Derived2 implements Base<Double>{
private Double x = 6.3;
String getName(){
return "Name: " + x;
}
List<Object> getChildren(){
return new List<>();
}
}
我正在按如下方式创建序列化程序:
JsonSerializer customAdapter = new JsonSerializer<Base>(){
@Override
JsonElement serialize(Base base, Type sourceType, JsonSerializationContext context){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", base.getName());
JsonArray jsonArray = new JsonArray();
for (Object child : base.getChildren()){
jsonArray.add(context.serialize(child));
}
if (jsonArray.size() != 0){
jsonObject.add("children", jsonArray);
}
}
};
Gson customSerializer = new GsonBuilder()
.registerTypeAdapter(Base.class, customAdapter)
.create();
但是,将我的自定义序列化程序应用于List 的子类并没有达到预期的效果。
customSerializer.toJson(Lists.newArrayList(new Derived1(), new Derived2()));
这会将默认的 GSON 序列化应用于我的子类。有什么简单的方法可以让我的自定义序列化程序在父类的所有子类上使用我的自定义适配器?我怀疑一种解决方案是使用反射来遍历Base 的所有子类并注册自定义适配器,但如果可能的话,我想避免这样的事情。
注意:我现在不关心反序列化。
【问题讨论】:
-
不要使用
JsonSerializer<Base>只是JsonSerializer并在覆盖方法中使用Object并检查并强制转换为Base -
这没有任何作用。
标签: java json serialization gson