将基础 class 从 java 中的反序列化集合中继承 class

Cast base class to inherited class from deserialized collection in java

我有一个基地class

SocialRecord.java

public class SocialRecord{

    private long id;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

}

和两个派生的classes

SocialEmailRecord.java

public class SocialEmailRecord extends SocialRecord{

        private String subject;

        public String getSubject() {
            return subject;
        }

        public void setSubject(String subject) {
            this.subject = subject;
        }
}

SocialDiscussionRecord.java

public class SocialDiscussionRecord extends SocialRecord{

    private String source;

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

}

我创建了一些 SocialEmailRecord 和 SocialDiscussionRecord 实例 classes.

SocialEmailRecord r1 = new SocialEmailRecord();
r1.setSubject("sub1");
SocialEmailRecord r2 = new SocialEmailRecord();
r2.setSubject("sub2");
SocialDiscussionRecord r3 = new SocialDiscussionRecord();
r3.setSource("source3");
SocialDiscussionRecord r4 = new SocialDiscussionRecord();
r4.setSource("source4");

我将这些对象添加到一个集合中。

List<SocialRecord> records = new ArrayList<>(Arrays.asList(r1, r2, r3, r4));

我用gson序列化了这个合集

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String objsInJson = gson.toJson(records);

现在我想反序列化这个集合,但是我不知道如何构造集合的原始对象。

Type listType = new TypeToken<ArrayList<Object>>() {}.getType();
List records = new ArrayList<>(Arrays.asList(graphUtils.getGson().fromJson(objsInJson), listType)));

我试过了,但没用。

for (int i = 0; i < records.size(); i++){
            if (records.get(i).getClass().equals(SocialDiscussionRecord.class))
                records.set(i, (SocialDiscussionRecord) records.get(i));
            if (records.get(i).getClass().equals(SocialPhoneRecord.class))
                records.set(i, (SocialPhoneRecord) records.get(i));
            if (records.get(i).getClass().equals(SocialEmailRecord.class))
                records.set(i, (SocialEmailRecord) records.get(i));
            if (records.get(i).getClass().equals(SocialRecord.class))
                records.set(i, (SocialRecord) records.get(i));
        }

您将必须实施 TypeHierarchyAdapterregister it to the GsonBuilder 来管理每个子类的特性的反序列化。

See here for a full classical example with Employee/Manager

但是即使对象实例是实际的 SocialEmailRecordSocialDiscussionRecord,您也会得到一个 ArrayList<SocialRecord>。您需要在 SocialRecord 中定义一些方法,这些方法将在子类中被覆盖,并使用多态性来处理列表。