簡體   English   中英

兒童的序列化和反序列化

[英]Serialization and deserialization of children

假設我具有以下結構:

abstract class foo{}
class bar1 extends foo{
     int demo1 = 0;
}
class bar2 extends foo{
     int demo1 = 0;
     int demo2 = 0;
}
class bar3 extends foo{}

通常,當我需要發送Json時,我使用以下代碼

Gson gson = new Gson()
gson.toJson(bar1);

收貨結束

Gson gson = new Gson()
bar1 test = gson.fromJson(gsonString, bar1);

這里的問題是,我需要發送bar1 / bar2 / bar3並返回原始對象- 意味着我不知道當前的JSON應該解析回什么 由於發送了bar1 / bar2 / bar3數組,因此增加了另一層復雜性。

例如:

//Issue: is the second param bar1 bar2 or bar3?
//I put a questionmark where the issues occur, due to the fact 
//that I wouldn't know on the recieving side whether I'm going 
//to recieve bar1/bar2/bar3
? test = gson.fromJson(gsonString, ?);

我嘗試將類型存儲在foo中,但是無法將其解析回去,所以無法知道類型。

如果您將類型存儲在Foo中,如下所示:

private String fqcn; 

您可以在接收時首先對json字符串進行字符串搜索,以提取完全合格的類名。 然后,您可以使用:

Foo test = gson.fromJson(gsonString, Class.forName( foundFqcn);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM