使用 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 数据。

  

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

 

 三、打印结果。

1) System.out.println(rows);

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

 

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

{"page":1,"total":3,"records":3,

"rows":

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

}

 

你可能感兴趣的:(json-lib)