使用Struts 2内置JSON实用程序类

在Struts 2项目中,我们需要序列化和反序列化对象,因为我们的要求非常简单,我们决定使用Struts 2 JSONUtil而不是gson

 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 map = (HashMap) JSONUtil.deserialize(string) accountVo.setAccountNumber(map.get("accountNumber")); .... 

我可以做得更好,或者我对这个实用程序的期望太高了。

在反序列化JSON之后,可以使用JSONPopulator从地图填充bean属性。 例如

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