Gson and abstract superclasses: deserialization issue

后端 未结 1 1354
悲哀的现实
悲哀的现实 2021-01-02 04:21

Suppose to have an abstract class, say A, and two non-abstract subclasses, say A1 and A2. I want to \"deserialize\" t

相关标签:
1条回答
  • 2021-01-02 04:35

    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);
    
    0 讨论(0)
提交回复
热议问题