Datatable/Dataset 转 JSON方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;

/// <summary>
///DataHelper 的摘要说明
/// </summary>
public class DataHelper
{
    public DataHelper()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
    #region DataTable转Json
    /// <summary>
    /// DataTable转Json for DataGrid
    /// </summary>
    /// <param name="_dt"></param>
    /// <returns></returns>
    public static string ToDataGrid(DataTable _dt)
    {
        string GridJson = string.Empty;
        try
        {
            GridJson = "{\"total\":" + _dt.Rows.Count + ",\"rows\":[";
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                GridJson += "{";
                string strTemp = "";
                for (int j = 0; j < _dt.Columns.Count; j++)
                {
                    strTemp = (j == _dt.Columns.Count - 1 ? "" : ",");
                    GridJson += "\"" + _dt.Columns[j].ColumnName.ToString() + "\":\"" + _dt.Rows[i][j].ToString().Trim() + "\"" + strTemp;
                }
                strTemp = (i == _dt.Rows.Count - 1 ? "}" : "},");
                GridJson += strTemp;
            }
            GridJson += "]}";
            //  Rev_DBPublic.Rev_WriteLog.WriteLog("PubErrorLogPath", "ToDataGrid" + "123", GridJson);
        }
        catch (Exception ee)
        {
            Rev_DBPublic.Rev_WriteLog.WriteLog("PubErrorLogPath", "ToDataGrid" + "123", GridJson + "Err:" + ee.Message);
        }
        return GridJson;
    }
    #endregion
    /// <summary>
    /// 将Datatable 中得数据行进行分页,并将页内数据返回
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="pageSize">行数</param>
    /// <param name="pageIndex">第几页</param>
    /// <returns></returns>
    public static DataTable DataTableToPager(DataTable dt, int pageSize, int pageIndex)
    {
        if (dt == null || dt.Rows.Count == 0)
        {
            return dt;
        }
        DataTable returnValue = null;

        DataColumn dc = new DataColumn("rowindex", Type.GetType("System.Int32"));
        dt.Columns.Add(dc);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["rowindex"] = i;
        }

        int _start = (pageIndex - 1) * pageSize;
        int _end = _start + pageSize;

        DataView dv = dt.DefaultView;
        dv.RowFilter = string.Format("rowindex>={0} and rowindex<{1}", _start, _end);
        returnValue = dv.ToTable();
        return returnValue;

    }
    #region DataTable转Json
    /// <summary>
    /// DataTable转Json for DataGrid
    /// </summary>
    /// <param name="_dt"></param>
    /// <returns></returns>
    public static string ToDataGridPage(DataTable _dt, int _row)
    {
        string GridJson = "{\"total\":" + _row + ",\"rows\":[";
        for (int i = 0; i < _dt.Rows.Count; i++)
        {
            GridJson += "{";
            string strTemp = "";
            for (int j = 0; j < _dt.Columns.Count; j++)
            {
                strTemp = (j == _dt.Columns.Count - 1 ? "" : ",");
                GridJson += "\"" + _dt.Columns[j].ColumnName.ToString() + "\":\"" + _dt.Rows[i][j].ToString() + "\"" + strTemp;
            }
            strTemp = (i == _dt.Rows.Count - 1 ? "}" : "},");
            GridJson += strTemp;
        }
        GridJson += "]}";
        //  Rev_DBPublic.Rev_WriteLog.WriteLog("PubErrorLogPath", "ToDataGrid" + "123", GridJson);
        return GridJson;
    }
    #endregion

    #region DataTable转Json
    /// <summary>
    /// DataTable转Json for DataGrid
    /// </summary>
    /// <param name="_dt"></param>
    /// <returns></returns>
    public static string ToDataGridPage(DataTable _dt, int _row, int page, int records)
    {
        string GridJson = "{\"page\":" + page + ",\"total\":" + _row + ",\"records\":" + records + ",\"rows\":[";
        for (int i = 0; i < _dt.Rows.Count; i++)
        {
            GridJson += "{";
            string strTemp = "";
            for (int j = 0; j < _dt.Columns.Count; j++)
            {
                strTemp = (j == _dt.Columns.Count - 1 ? "" : ",");
                GridJson += "\"" + _dt.Columns[j].ColumnName.ToString() + "\":\"" + _dt.Rows[i][j].ToString() + "\"" + strTemp;
            }
            strTemp = (i == _dt.Rows.Count - 1 ? "}" : "},");
            GridJson += strTemp;
        }
        GridJson += "]}";
        //  Rev_DBPublic.Rev_WriteLog.WriteLog("PubErrorLogPath", "ToDataGrid" + "123", GridJson);
        return GridJson;
    }
    #endregion

    #region dataTable转换成Json格式
    /// <summary>
    /// dataTable转换成Json格式
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static string DataTable2Json(DataTable dt)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        if (dt.Rows.Count > 0)
        {
            jsonBuilder.Append("]");
        }
        return jsonBuilder.ToString();
    }

    #endregion dataTable转换成Json格式
}
时间: 2024-12-28 02:14:30

Datatable/Dataset 转 JSON方法的相关文章

.NET DataTable DataSet转json代码

/// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string ToJson(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilde

DataSet转Json 方法

防止忘记,留着备用 /// <summary> /// DATASET转JSON /// </summary> /// <param name="ds"></param> /// <returns></returns> public static string ToJson(DataSet ds) { try { string json = "["; foreach (DataRow i in

Asp.net 将DataTable 或者DataSet 转换为Json 格式

Web 开发中,将从数据库中取到的数据直接转换为 Json 格式的数据,在前台通过Ajax 无刷新显示在界面上,下面提供将DataTable 或者DataSet 转换为Json 的方法 /// <summary> /// DataTable 转换成Json 操作类 /// </summary> public static class ConvertJson { #region DataSet转换为Json /// <summary> /// DataSet转换为Json

C#将datatable数据转换成JSON数据的方法

json数据类型格式:[{id:"1",code:"1",description:"博士"},{id:"2",code:"2",description:"硕士"},{id:"3",code:"3",description:"学士"}] //参考代码public string DataTableToJson(string json

DataTable 转换成 Json的3种方法

在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,Ajax异步请求的数据格式就是Json.鉴于此,我今天来分享将DataTable 转换成 Json的3种方法.换句话说如何在ASP.NET将一个DataTable序列化为 Json数组.或者如何从一个DataTable返回一个Json字符串.这篇文章将采用StringBuilder,JavaScriptSeri

datatable和dataset转json

using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; using System.Web.Script.Serialization; /// <summary> /// JsonConvert 的摘要说明 /// </summary> public class JsonConvert { #re

.NET-DataTable或DataSet转JSON

通过AJAX异步减少网络内容传输,而JSON则可以把传输内容缩减到纯数据:然后利用jQuery内置的AJAX功能直接获得JSON格式的数据:在客户端直接绑定到数据控件里面,从而达到最优. #region dataTable转换成Json格式 /// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"></param> /// <returns>

C#中DataTable中的Compute方法使用收集

原文: C#中DataTable中的Compute方法使用收集 Compute函数的参数就两个:Expression,和Filter. Expresstion是计算表达式,关于Expression的详细内容请看这里“http://msdn2.microsoft.com/zh-cn/library/system.data.datacolumn.expression(VS.80).aspx”.而Filter则是条件过滤器,类似sql的Where条件. DataTable dt = new DataT

ASP.NET 将DataTable解析成JSON简介

这里解析json使用的是Newtonsoft.Json.dll程序集.下面请看code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using Newtonsoft.Json; /// <summary> ///DataTable解析JSON /// </summary> public class ConvertDat