日期:2014-05-16 浏览次数:20388 次
class UserInfo{ String username; String password; List<String> subName; Map<String,String> map; Privileges[] privileges; Privileges privilegesObj; { username = "zhangsan"; password = "zhangsnaPass"; subName = new ArrayList<String>(); subName.add("aabc"); subName.add("lisi"); map = new HashMap<String,String>(); map.put("u1", "v1"); map.put("u2", "v2"); privileges = new Privileges[2]; Privileges priv1 = new Privileges(); priv1.setPriviName("delete img res"); Privileges priv2 = new Privileges(); priv2.setPriviName("add music res"); privileges[0]=priv1; privileges[1]=priv2; privilegesObj = new Privileges(); privilegesObj.setPriviName("test res iffo"); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<String> getSubName() { return subName; } public void setSubName(List<String> subName) { this.subName = subName; } public Map<String, String> getMap() { return map; } public void setMap(Map<String, String> map) { this.map = map; } public Privileges[] getPrivileges() { return privileges; } public void setPrivileges(Privileges[] privileges) { this.privileges = privileges; } }
class Privileges{ String priviName; public String getPriviName() { return priviName; } public void setPriviName(String priviName) { this.priviName = priviName; } }
public static void main(String[] args) { Gson gson = new Gson(); String json = null; UserInfo userinfo = new UserInfo(); json = gson.toJson(userinfo); System.out.println("userinfo json str:"+json); //userinfo json str:{"username":"zhangsan","password":"zhangsnaPass","subName":["aab","lisi"],"map":{"u2":"v2","u1":"v1"},"privileges":[{"priviName":"delete img res"},{"priviName":"add music res"}],"privilegesObj":{"priviName":"test res iffo"}} json = "{\"username\":\"zhangsan\",\"password\":\"zhangsnaPass\",\"subName\":[\"list1\",\"list2\"],\"map\":{\"u2\":\"v2\",\"u1\":\"v1\"},\"privileges\":[{\"priviName\":\"delete img res\"},{\"priviName\":\"add music res\"}],\"privilegesObj\":{\"priviName\":\"test res iffo\"}}"; userinfo = gson.fromJson(json, UserInfo.class); System.out.println(userinfo); }