具有Gson序列化/反序列化的抽象类

ryhaxcpt  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(289)

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

@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,但是在反序列化时崩溃(可能是抽象类或者/并且我期待一个LinkedList和/或lombok注解)?我试着写一个gson反序列化器(在谷歌上找到了一个相当标准的反序列化器),但是它没有完成这项工作。

ffx8fchx

ffx8fchx1#

多亏了@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编写构造函数和getter/setter

相关问题