将 数据库中的结果集转换为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小生店铺

希望店铺的资料能帮助到你!!!

 

原文地址:https://www.cnblogs.com/lirenzhujiu/p/5915635.html