摘要 class 与 Gson serialization/deserialization

Abstract class with Gson serialization/deserialization

我希望从 json 得到 LinkedList<Request>。 pojo 看起来像这样:

@Data
@Builder
public class Request {
    private String id;
    private List<Parameter> parameters;
}

@Data
@SuperBuilder
public abstract class Parameter implements Serializable {
    private String key;
    public abstract Object getValue();
}

@Data
@SuperBuilder
@EqualsAndHashCode(callSuper = true)
public class StringParameter extends Parameter implements Serializable {
    private String value;
}

@Data
@SuperBuilder
@EqualsAndHashCode(callSuper = true)
public class PasswordParameter extends Parameter implements Serializable {
    private String value;
}

序列化工作正常,它生成 json,但它在反序列化时崩溃(可能是抽象 class or/and,我期待 LinkedList and/or 龙目岛注释)? 我尝试编写一个 gson 反序列化器(谷歌搜索发现的一个非常标准的反序列化器),但它没有完成这项工作。

感谢@fluffy 的建议,我设法跳过编写自定义反序列化器并使用 gson-extras 库中的 RuntimeTypeAdapterFactory

public static void writeObjectToFile(Object object, String filePath) {
      RuntimeTypeAdapterFactory<Parameter> parameterAdapterFactory = RuntimeTypeAdapterFactory.of(Parameter.class, "type");
      parameterAdapterFactory.registerSubtype(StringParameter.class, "StringParameter");
      parameterAdapterFactory.registerSubtype(PasswordParameter.class, "PasswordParameter");
      Gson gson = new GsonBuilder().setPrettyPrinting().registerTypeAdapterFactory(parameterAdapterFactory).create();
      try {
          FileWriter fileWriter = new FileWriter(filePath);
          gson.toJson(object, fileWriter);
          fileWriter.flush();
          fileWriter.close();
      } catch (IOException e) {
          System.out.println(e.getMessage());
      }
  }

  public static LinkedList<Request> readObjectFromFile(String filePath) {
      RuntimeTypeAdapterFactory<Parameter> parameterAdapterFactory = RuntimeTypeAdapterFactory.of(Parameter.class, "type");
      parameterAdapterFactory.registerSubtype(StringParameter.class, "StringParameter");
      parameterAdapterFactory.registerSubtype(PasswordParameter.class, "PasswordParameter");
      Gson gson = new GsonBuilder().setPrettyPrinting().registerTypeAdapterFactory(parameterAdapterFactory).create();
      try {
          BufferedReader jsonBuffer = new BufferedReader(new FileReader(filePath));
          return gson.fromJson(jsonBuffer, new TypeToken<LinkedList<Request>>(){}.getType());
      } catch (FileNotFoundException e) {
          System.out.println(e.getMessage());
      }
      return  null;
  }

我也只保留了 lombok 注释,没有为我的 POJO 编写构造函数和 getters/setters