JavaBean,List,Map转成json格式

JavaBean,List,Map转成json格式
JavaBean,List,Map转成json格式

response.getWriter().print(jsonObj);

在js文件取数据

alert(https://www.360docs.net/doc/0710863400.html,ername);

alert(data.password);

List转成json格式

Listusers=new ArrayList();

User user=new User();

user.setUsername("cxl");

user.setPassword("1234");

User u=new User();

u.setUsername("lhl");

u.setPassword("1234");

users.add(user);

users.add(u);

1.转成JSONArray类型

JSONArray json=JSONArray.fromObject(users);

System.out.println(json.toString());

//[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}]

response.getWriter().print(json.toString());

js中取数据:alert(alert(data[0].username));

2.转成JSONObject类型

不可直接使用JSONObject jsonObj=JSONObject.fromObject(users);

可通过下列方式

JSONObject jsonObj=new JSONObject();

jsonObj.put("users",users);

jsonObj.put("u",u);

System.out.println(jsonObj);

{"users":[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}],

"u":{"password":"1234","username":"lhl"}}

response.getWriter().print(jsonObj);

js中取数据:alert(https://www.360docs.net/doc/0710863400.html,ers[0].username);

alert(data.u[0].username);

Map转成json格式

Mapmap=new HashMap();

map.put("users",users);

map.put("u",u);

1.转成JSONArray类型

JSONArray json=JSONArray.fromObject(map);

System.out.println(json.toString());//

[{"users":[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}],"u":{"password":"1

234","username":"lhl"}}]

response.getWriter().print(json.toString);

js中取数据:alert(data[0].users[0].username);

2.转成JSONObject类型

JSONObject json=JSONObject.fromObject(map);

System.out.println(json);//

{"user":[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}],"u":{"password":"12 34","username":"lhl"}}

response.getWriter().print(json);

js中取数据:alert(https://www.360docs.net/doc/0710863400.html,er[0].username);

相关主题
相关文档
最新文档