遵循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 fullName = typeOfT.getTypeName(); String packageText = fullName.substring(0, fullName.lastIndexOf(".") + 1); return context.deserialize(element, Class.forName(packageText + type)); } catch (ClassNotFoundException cnfe) { throw new JsonParseException("Unknown element type: " + type, cnfe); } }}然后进行序列化,如下所示:
GsonBuilder gson = new GsonBuilder();gson.registerTypeAdapter(A.class, new ATypeAdapter());String json = gson.create().toJson(list);
并给出json字符串,反序列化为:
GsonBuilder gson = new GsonBuilder();gson.registerTypeAdapter(A.class, new ATypeAdapter());return gson.create().fromJson(json, A[].class);



