Java 使用Struts 2内置JSON实用程序类
在Struts 2项目中,我们需要序列化和反序列化对象,因为我们的需求非常简单,我们决定使用Struts 2Java 使用Struts 2内置JSON实用程序类,java,json,struts2,Java,Json,Struts2,在Struts 2项目中,我们需要序列化和反序列化对象,因为我们的需求非常简单,我们决定使用Struts 2JSONUtil而不是gson import org.apache.struts2.json; String json = JSONUtil.serialize(myAccountVO); // return: {"accountNumber":"0105069413007","amount":"1500","balance":"215000"} 对于反序列化,我们面临类强制转换异常
JSONUtil
而不是gson
import org.apache.struts2.json;
String json = JSONUtil.serialize(myAccountVO);
// return: {"accountNumber":"0105069413007","amount":"1500","balance":"215000"}
对于反序列化
,我们面临类强制转换异常
AccountVO vo =(AccountVO) JSONUtil.deserialize(json);
//Exception
我发现,反序列化
返回一个带有对象属性键值的映射。因此,我必须这样做:
HashMap<String,String> map = (HashMap) JSONUtil.deserialize(string)
accountVo.setAccountNumber(map.get("accountNumber"));
....
HashMap=(HashMap)JSONUtil.deserialize(string)
accountVo.setAccountNumber(map.get(“accountNumber”));
....
我可以做得更好,或者我对这个实用程序期望太高。在反序列化JSON之后,可以使用从映射填充bean属性。例如
JSONPopulator populator = new JSONPopulator();
AccountVO vo = new AccountVO();
populator.populateObject(vo, map);