Alireza Fattahi
Alireza Fattahi

Reputation: 45475

Using Struts 2 builtin JSON utility class

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"}

For deserialization, we face the class cast exception

    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.

Upvotes: 2

Views: 501

Answers (1)

Roman C
Roman C

Reputation: 1

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);

Upvotes: 2

Related Questions