將 數據庫中的結果集轉換為json格式(三)


從數據庫中得到結果集

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 1234567@qq2233.com
            // 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;
    }

對結果集進行轉換成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;
    }
}

 

Java小生店鋪:

Pc端:http://shop125970977.taobao.com/index.htm

手機端:搜索 java小生店鋪

希望店鋪的資料能幫助到你!!!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM