2011-06-05 64 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

我会问的第一个问题是如果代码抛出异常?如果不是,则检查该对象并将属性/对象设置为默认状态,因为如果没有发送数据,则无法检索数据。或者在对象的构造函数中添加初始化代码,以便反序列化程序将有一个初始化对象。