2016-11-12 127 views
-1
的反序列化

假設我有以下結構:系列化和兒童

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

Recieving結束

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

這裏的問題是我需要發送b ar1/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的類型,但沒有能夠解析回來也沒有辦法知道的類型。

+0

不清楚你在問什麼。 'GSon.fromJson()'返回一個你忽略的值,那麼它怎麼會有一個問題呢? – EJP

+0

我不會無視它!根據參數中的對象,它返回該對象。問題是我不知道Json收到的是什麼對象。 – Gabrielus

+0

'gson.fromJson(gsonString,bar1);'不會將結果存儲到變量中,* ergo *它會忽略它。 – EJP

回答

2

如果您存儲這樣的富類型:當接收

private String fqcn; 

的,你可以先做的JSON字符串的字符串搜索,提取完全合格的類名。然後你可以使用:

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

你可以嘗試解析try-catch塊中的類。當拋出異常時,抓住它並再次嘗試將其解析到下一個類。

+0

downvotes可能有2個原因:1)Gson不拋出錯誤,當某些東西不能完全解析成一個對象2)不是很好的做法 – Gabrielus

+0

我很欣賞你的輸入,雖然:) – Gabrielus