Datatable/Dataset 转 JSON方法

Posted 小飛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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格式
}

 

以上是关于Datatable/Dataset 转 JSON方法的主要内容,如果未能解决你的问题,请参考以下文章

Json与DataSet转化

datatable dataset

C# DataSet与DataTable的区别和用法

C# DataSet与DataTable的区别和用法

DataTable 和 DataSet 现在应该过时了吗?

从 DataTable/DataSet 中的搜索创建 DataRow