使用 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<String,String> 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);

最新更新