進行資料的查詢得到的 ResultSet 進行轉成json (通過這種方式好像時間類型的轉成json之後可能不是你想要的那種樣式 具體可以測試一下)
package com.java1234.util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.mysql.jdbc.ResultSetMetaData;
public class JsonUtil {
/**
* 把ResultSet集合轉換成JsonArray數組
*
* @param rs
* @return
* @throws Exception
*/
public static JSONArray formatRsToJsonArray(ResultSet rs) throws Exception {
ResultSetMetaData md = rs.getMetaData();// 擷取表結構
int num = md.getColumnCount();// 得到行的總數
JSONArray array = new JSONArray();// json數組,根據下标找值;[{name1:wp},{name2:{name3:'ww'}}]name為key值,wp為value值
// JSONArray array=JSONArray.fromObject(String);将String轉換為JSONArray格式
while (rs.next()) {// 如果結果集中有值
JSONObject mapOfColValues = new JSONObject();// 建立json對象就是一個{name:wp}
for (int i = 1; i <= num; i++) {
mapOfColValues.put(md.getColumnName(i), rs.getObject(i));// 添加鍵值對,比如說{name:Wp}通過name找到wp
System.out.println(mapOfColValues.toString());
}
array.add(mapOfColValues);
}
return array;
}
}
public String list() throws Exception {
Connection con = null;
PageBean pageBean = new PageBean(Integer.parseInt(page), Integer
.parseInt(rows));
try {
con = dbUtil.getCon();
JSONObject result = new JSONObject();
JSONArray jsonArray = JsonUtil.formatRsToJsonArray(userDao.userList(con, pageBean));// 得到的資料如:
// 張三12233 12345672233 [email protected]
// 12345672233原來是緊密在一起的字元串,然後将這串結果集轉換成json數組,進行格式化
int total = userDao.userCount(con);// 得到總數
result.put("rows", jsonArray);
result.put("total", total);// 顯示本頁總數
ResponseUtil.write(ServletActionContext.getResponse(), result);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}