使用Struts 2内置JSON实用程序类 [英] Using Struts 2 builtin JSON utility class

查看:167
本文介绍了使用Struts 2内置JSON实用程序类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In an Struts 2 project, we need to serialize and deserialize objects, as our requirement is very simple, we decide to use Struts 2 JSONUtil instead of 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

我发现反序列化返回具有对象属性键值的映射。所以我必须这样做:

I find that the deserialization returns a map with key value of object properties. So I must do as:

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

我可以做得更好还是我期待太多此实用程序。

Well can I do it better or I am expecting too much from this utility.

推荐答案

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

After you have deserialized JSON, you can use JSONPopulator to populate bean properties from a map. E.g.

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

这篇关于使用Struts 2内置JSON实用程序类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆