2011-06-05 89 views
1

我們有兩個系統:外部和內部,它們以JSON格式共享信息(GSON庫)。如何反序列化,如果缺少某個日期?

來自外部系統的信息進入內部並在此處理。

一切都非常好,來自JSON格式的外部系統數據在內部系統數據反序列化和處理。例如:

來字符串:

{UserLogInEvent:{userName:'Name', time:'00.00.00'}} 

在這個類的對象此字符串反序列化:

UserLogInEvent implement Event { 

private String userName; 
private Date time; 

public UserLogInEvent (String userName, Date time) 
{ 
this.userName = userName; 
this.time = time; 
} 

private UserLogInEvent() 
{ 
this.userName = null; 
this.time = null; 
} 

public String getUserName() 
{ 
return this.userName; 
} 
public Date time() 
{ 
return this.time; 
} 
} 

或其他例如:

{UserModifyFile: {userName:'Name',fileName: 'index.txt' time:'00.00.00'}} 



UserModifyEvent implement Event { 

private String userName; 
private String fileName; 
private Date time; 

public UserLogInEvent (String userName, String fileName, Date time) 
{ 
this.userName = userName; 
this.fileName = fileName; 
this.time = time; 
} 

private UserLogInEvent() 
{ 
this.userName = null; 
this.fileName = null; 
this.time = null; 
} 

public String getUserName() 
{ 
return this.userName; 
} 
public Date time() 
{ 
return this.time; 
} 
public String getFileName() 
{ 
return this.fileName; 
} 
} 

的算法非常簡單:

string -> deserialization -> object events created. 

但是..進一步的問題開始了。這些問題我不能決定。

增加了新的事件。

隨外部系統信息不包含有關該事件的所有必要的數據,例如:

{UpdateProductInfoEvent: {userName:'name', time: '00.00.00', product: {id:'123', name: '???', type: '???', cost:'???'}}} 

正如你可以看到,該行不包含所有的數據...只是不反序列化給出想要的結果...

要做到這一點,我仍然需要調用一個方法,通過它的Id接收關於產品的信息。

的算法如下:

JSON string -> processing line -> product information from ID -> object creation * Event. 

下面的例子:

{ModifyProductCatalogEvent:{userName: 'Name', time: '00.00.00', catalog:{id:'321', catalogType:'???', catalogName: '????'}}} 

我又沒有關於目錄中的所有信息...

所以,我尋求幫助,如何在缺乏數據的情況下正確構造一個算法來創建對象?

回答

1

您可以通過覆蓋編寫自己的序列化和反序列化方法:

private void writeObject(java.io.ObjectOutputStream out) 
    throws IOException 
private void readObject(java.io.ObjectInputStream in) 
    throws IOException, ClassNotFoundException; 

使您自己處理這些情況。您仍然可以通過使用out.defaultWriteObject/in.defaultReadObject來使用缺省方法,只需處理數據可能丟失的情況(或者如果您有無效對象的默認值,請使用常規方法讀取所有字段,然後覆蓋具有正確數據的無效字段)。

+0

但是,如果在位置GSON lib看這種情況? – user471011 2011-06-05 14:37:45

+0

從未使用GSON,但由於快速瀏覽顯示可以編寫自己的JsonDeserializer實現,它應該以類似的方式工作.. – Voo 2011-06-05 15:08:09

+0

好的,謝謝! – user471011 2011-06-05 18:25:24

0

我會問的第一個問題是如果代碼拋出異常?如果不是,則檢查該對象並將屬性/對象設置爲默認狀態,因爲如果沒有發送數據,則無法檢索數據。或者在對象的構造函數中添加初始化代碼,以便反序列化程序將有一個初始化對象。