码迷,mamicode.com
首页 > 数据库 > 详细

从数据库中的到数据对其转换为json格式(三)

时间:2016-09-28 12:16:50      阅读:1297      评论:0      收藏:0      [点我收藏+]

标签:

从数据库中得到结果集

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;
    }
}

 

从数据库中的到数据对其转换为json格式(三)

标签:

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

(1)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!