Suppose to have an abstract class, say A
, and two non-abstract subclasses, say A1
and A2
. I want to \"deserialize\" t
Following the Axxiss link, here follows the answer. A custom serializer/deserializer must be provided.
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);
}
}
}
Then the serialization is done like follows:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(A.class, new ATypeAdapter());
String json = gson.create().toJson(list);
and given the json string, the deserialization is:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(A.class, new ATypeAdapter());
return gson.create().fromJson(json, A[].class);