Gson反序列化多态列表:Gson找不到正确的子类型

时间:2019-05-19 11:05:25

标签: java json gson deserialization

我想存储一个多态对象列表,并且我一直在使用RuntimeTypeAdapterFactory类。基类为Student(抽象),其子类为UndergraduateMastersPHD。这是我的序列化:

    private static final TypeToken STUDENT_SERIAL_TYPE
            = new TypeToken<Student>() {
            };

    private static StudentsDA instance = null;

    // Save subclasses (polymorphic) locally
    RuntimeTypeAdapterFactory<Student> adapter = RuntimeTypeAdapterFactory
            .of(Student.class, "type")
            .registerSubtype(Undergraduate.class)
            .registerSubtype(Masters.class)
            .registerSubtype(PHD.class);

    private Gson getGson() {
        return new GsonBuilder()
                .setPrettyPrinting()
                .registerTypeAdapterFactory(adapter)
                .create();
    }

    //....

    public void saveStudents(List<Student> students) {

        String studentsJson = getGson().toJson(students);

        saveStudentsLocally(studentsJson);
    }

保存的很好,该类型已注册为我

public final String type = getClass().getName();

at Student.java

这是我的反序列化部分:

    public List<Student> getStudents() {

        JsonParser parser = new JsonParser();
        JsonArray stdArray = parser.parse(loadStudentsData()).getAsJsonArray();

        List<Student> students = new ArrayList<>();
        for (JsonElement jsonElement : stdArray) {
            Student s = getGson().fromJson(jsonElement, STUDENT_SERIAL_TYPE.getType());
            students.add(s);
        }

        return students;
    }

但是当我打电话给getStudents()时,它会引发以下错误:

Exception in thread "AWT-EventQueue-0" com.google.gson.JsonParseException: cannot deserialize class main.models.Student subtype named main.models.Masters; did you forget to register a subtype?

我一直在关注this article,所以我错过了什么吗?

0 个答案:

没有答案