Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用Struts 2内置JSON实用程序类_Java_Json_Struts2 - Fatal编程技术网

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

Java 使用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"} 对于反序列化,我们面临类强制转换异常

在Struts 2项目中,我们需要序列化和反序列化对象,因为我们的需求非常简单,我们决定使用Struts 2
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);