将基类转换为java中反序列化集合的继承类

时间:2015-04-01 20:21:41

标签: java json serialization casting deserialization

我有一个基类

SocialRecord.java

public class SocialRecord{

    private long id;

    public long getId() {
        return id;
    }

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

}

和两个派生类

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类的一些实例。

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));
        }

1 个答案:

答案 0 :(得分:2)

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

See here for a full classical example with Employee/Manager

但即使对象实例是实际ArrayList<SocialRecord>SocialEmailRecord,您也会获得SocialDiscussionRecord。您需要在SocialRecord中定义一些方法,这些方法应在子类中重写并使用多态来处理列表。