日期:2014-05-16  浏览次数:20425 次

json中关于处理数据的方法 json-lib
一、相关资料





1、json-lib 参考网站:http://json-lib.sourceforge.net/

2、下载:http://sourceforge.net/projects/json-lib/files/json-lib/

3、json-lib 的版本。

  依据对jdk 的匹配,Json-lib有两个版本:

1) x-jdk13匹配于JDK 1.3.1及更高版本。

2)x-jdk15匹配于JDK 1.5,包括在JSONArray 和JSONObject中对Enums 的支持。

4、json-lib的依赖包(基于 json-lib-2.3-jdk15.jar )。

1)commons-lang-2.6.jar

2)commons-beanutils-1.8.3.jar

3)commons-collections-3.2.1.jar

4)commons-logging-1.1.1.jar

5)ezmorph-1.0.6.jar





二、例:使用json-lib 处理数据,类似为DataGrid 数据。

 

Java代码 
1.JSONObject jsonObject = new JSONObject();  
2. 
3. jsonObject.put("page", 1); // 当前页  
4.  jsonObject.put("total", 3); // 总页数  
5. jsonObject.put("records", 3); // 总记录数  
6. 
7.UserDaoImpl userDaoImpl=new UserDaoImpl();  
8. ArrayList<User> userList=userDaoImpl.getUserList();  
9. JSONArray rows=JSONArray.fromObject(userList); // 用JSONArray 存储List的数据  
10. 
11.jsonObject.put("rows", rows);  
12. 
13.System.out.println("要返回的json对象:\n" + jsonObject.toString()); 
JSONObject jsonObject = new JSONObject();

jsonObject.put("page", 1); // 当前页
  jsonObject.put("total", 3); // 总页数
jsonObject.put("records", 3); // 总记录数

UserDaoImpl userDaoImpl=new UserDaoImpl();
ArrayList<User> userList=userDaoImpl.getUserList();
JSONArray rows=JSONArray.fromObject(userList); // 用JSONArray 存储 JSONArray.fromObject() 转换的数据

jsonObject.put("rows", rows);

System.out.println("要返回的json对象:\n" + jsonObject.toString());



三、打印结果。

Java代码 
1.1) System.out.println(rows);  
2. 
3.[{"address":"合肥","email":"admin@163.com","password":"123456","sex":"男","telephone":"5394252","userId":1,"userName":"admin"},{"address":"上海","email":"zhangsan@163.com","password":"123456","sex":"男","telephone":"1394253","userId":2,"userName":"zhangsan"},{"address":"北京","email":"lisi@sohu.com","password":"123456","sex":"女","telephone":"5625321","userId":3,"userName":"lisi"}] 
1) System.out.println(rows);

[{"address":"合肥","email":"admin@163.com","password":"123456","sex":"男","telephone":"5394252","userId":1,"userName":"admin"},{"address":"上海","email":"zhangsan@163.com","password":"123456","sex":"男","telephone":"1394253","userId":2,"userName":"zhangsan"},{"address":"北京","email":"lisi@sohu.com","password":"123456","sex":"女","telephone":"5625321","userId":3,"userName":"lisi"}]



Java代码 
1.2)System.out.println("要返回的json对象:\n" + jsonObject.toString());  
2. 
3.{"page":1,"total":3,"records":3,  
4. 
5."rows":  
6. 
7.[{"address":"合肥","email":"admin@163.com","password":"123456","sex":"男","telephone":"5394252","userId":1,"userName":"admin"},{"address":"上海","email":"zhangsan@163.com","password":"123456","sex":"男","telephone":"1394253","userId":2,"userName":"zhangsan"},{"address":"北京","email":"lisi@sohu.com","password":"123456","sex":"女","telephone":"5625321","userId":3,"userName":"lisi"}]  
8. 
9.}