我们有两个系统:外部和内部,它们以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