我們有兩個系統:外部和內部,它們以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: '????'}}}
我又沒有關於目錄中的所有信息...
所以,我尋求幫助,如何在缺乏數據的情況下正確構造一個算法來創建對象?
但是,如果在位置GSON lib看這種情況? – user471011 2011-06-05 14:37:45
從未使用GSON,但由於快速瀏覽顯示可以編寫自己的JsonDeserializer實現,它應該以類似的方式工作.. – Voo 2011-06-05 15:08:09
好的,謝謝! – user471011 2011-06-05 18:25:24