2016-04-24 36 views
2

在Struts 2項目中,我們需要序列化和反序列化對象,因爲我們的要求非常簡單,我們決定使用Struts 2 JSONUtil而不是gson使用Struts 2內置JSON實用類

import org.apache.struts2.json; 

String json = JSONUtil.serialize(myAccountVO); 
// return: {"accountNumber":"0105069413007","amount":"1500","balance":"215000"} 

對於deserialization,我們所面臨的class cast exception

AccountVO vo =(AccountVO) JSONUtil.deserialize(json); 
    //Exception 

我發現deserialization返回對象屬性的鍵值的地圖。所以,我必須做的:

HashMap<String,String> map = (HashMap) JSONUtil.deserialize(string) 
accountVo.setAccountNumber(map.get("accountNumber")); 
.... 

那麼我可以做的更好或者我期待從這個工具太多。

回答

2

在反序列化JSON之後,可以使用JSONPopulator從映射填充bean屬性。例如。

JSONPopulator populator = new JSONPopulator(); 
AccountVO vo = new AccountVO(); 
populator.populateObject(vo, map);