假设有一个抽象类,比方说A,和两个非抽象的子类,比如说A1和A2.我想通过使用GSON库从json格式"反序列化"它们.
我得到一个A对象数组.
int n = ...;
A[] list = new A[n];
A[0] = new A1(....);
A[1] = new A2(....);
...
Run Code Online (Sandbox Code Playgroud)
有人转换为JSON字符串,如下所示:
String json = (new Gson()).toJson(list);
Run Code Online (Sandbox Code Playgroud)
最后,如果我尝试反序列化如下
A[] deserializedList = (new Gson()).fromJson(json, A[].class);
Run Code Online (Sandbox Code Playgroud)
然后我有一个错误,因为GSON默认的反序列化器找到一个抽象类(即A),它不能猜测子类类型.
我怎么解决这个问题?
PS:我读过有关自定义反序列化器的内容,但在这种情况下我不明白如何使用它们.
mat*_*boy 19
按照Axxiss链接,下面是答案.必须提供自定义序列化器/解串器.
public class AClassAdapter implements JsonSerializer<A>, JsonDeserializer<A> {
@Override
public JsonElement serialize(A src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.add("type", new JsonPrimitive(src.getClass().getSimpleName()));
result.add("properties", context.serialize(src, src.getClass()));
return result;
}
@Override
public A deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String type = jsonObject.get("type").getAsString();
JsonElement element = jsonObject.get("properties");
try {
String thepackage = "my.package.name.";
return context.deserialize(element, Class.forName(thepackage + type));
} catch (ClassNotFoundException cnfe) {
throw new JsonParseException("Unknown element type: " + type, cnfe);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后序列化完成如下:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(A.class, new ATypeAdapter());
String json = gson.create().toJson(list);
Run Code Online (Sandbox Code Playgroud)
并且给定json字符串,反序列化是:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(A.class, new ATypeAdapter());
return gson.create().fromJson(json,
A[].class);
Run Code Online (Sandbox Code Playgroud)