java中javabean、list、map格式转换为json格式

时间:2022-10-26 19:36:05

在使用json的时候,麻烦的是要吧java后台的各种数据转化为json格式输出,下面列举几种情况。

首先你要引入的包有:六个常用的包 1)commons-logging-1.0.4.jar、2)commons-lang-2.3.jar、3)commons-collections-3.2.jar 、4)commons-beanutils-1.7.0.jar、5)json-lib-2.2.1-jdk15.jar、6)ezmorph-1.0.4.jar


如果用到框架还要引用struts的插件jsonplugin.jar


普通JavaBean转成json格式 

1.转成JSONArray类型 

User user = new User()

user.setUsername("红领巾"); 

user.setPassword("1234"); 

JSONArray json = JSONArray.fromObject(user); 

System.out.println(json);//[{"password":"1234","username":"红领巾"}] 

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


2.转成JSONObject类型 

JSONObject jsonObj = JSONObject.fromObject(user); 

System.out.println(jsonObj);//{"password":"1234","username":"cxl"} 

response.getWriter().print(jsonObj); 

在js文件取数据 

alert(data.username); 

alert(data.password); 

List转成json格式 

List<User> users = new ArrayList<User>(); 

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(data.users[0].username); 

           alert(data.u[0].username); 
Map转成json格式 

Map<String,Object> map = new HashMap<String,Object>(); 

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":"1234","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":"1234","username":"lhl"}} 

response.getWriter().print(json); 

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


不要问我是谁,请叫我红领巾