示例类:
public class A
{
String Name;
List<B> GenericsList;
//Getters & Setters & Constructors
}
public class B
{
String Title;
//Getters & Setters & Constructors
}
public class C extends B
{
String Something;
//Getters & Setters & Constructors
}
如果我像这样序列化A类的实例:
List<B> bList = new ArrayList<>();
C bObj = new C("name", "something text");
bList.add(bObj);
A aObj = new A("name", bList);
String serialized = new Gson.toJson(aObj);
A deserializedA = new Gson.fromJson(serialized);
我在List中丢失了C子类型。 我知道如何解决这个问题,如果它只是一个像这样序列化的List:
Gson gson = new Gson();
List<B> bList = new ArrayList<>();
Type bType = new TypeToken<List<B>>() {}.getType();
gson.toJson(bList, bType);
gson.fromJson(json, bType);
问题是我的泛型列表位于具有其他参数的对象内。我该怎么做?
编辑1: 也许我不清楚具体问题。
当我序列化和反序列化上面创建的A对象时,没有错误,而是得到这个: 对象A: 名称=&#34;名称&#34; GenericsList = {Object C}
我得到: 对象A: 名称=&#34;名称&#34; GenericsList = {Object B}
我丢失了C型细节。
答案 0 :(得分:1)
知道了!感谢提示Sotirios Delimanolis!
必须为B类创建自定义实现:
class BGsonAdapter implements JsonSerializer<B>, JsonDeserializer<B>
{
public JsonElement serialize(B bObj, Type typeOfSrc, JsonSerializationContext context)
{
JsonObject result = new JsonObject();
result.add("Title", context.serialize(B.getTitle(), String.class));
if (bObj instanceof C)
{
result.add("Something", context.serialize(((C)bObj).getSomething(), String.class));
}
return result;
}
public B deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject object = json.getAsJsonObject();
B result = null;
if (object.has("Something"))
{
result = new C();
((C) result).setSomething((String)context.deserialize(object.get("Something"), String.class));
if (result == null)
{
result = new B();
}
result.setTitle(((String)context.deserialize(object.get("Title"), String.class)));
return result;
}
}
并像这样使用它:
Gson gson = new GsonBuilder()
.registerTypeHierarchyAdapter(B.class, new BGsonAdapter())
.setPrettyPrinting()
.create();
String serialized = gson.toJson(A);
A deserialized = (A)gson.fromJson(A);