当前位置:  编程技术>.net/c#/asp.net

C#中把Datatable转换为Json的5个代码实例

    来源: 互联网  发布时间:2014-10-30

    本文导语:  实例一: 代码如下:///          /// Datatable转换为Json         ///         /// Datatable对象         /// Json字符串         public static string ToJson(DataTable dt)    {        StringBuilder jsonString = new StringBuilder();      ...

实例一:

代码如下:

///     
    /// Datatable转换为Json    
    ///    
    /// Datatable对象    
    /// Json字符串    
    public static string ToJson(DataTable dt)
    {
        StringBuilder jsonString = new StringBuilder();
        jsonString.Append("[");
        DataRowCollection drc = dt.Rows;
        for (int i = 0; i < drc.Count; i++)
        {
            jsonString.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                string strKey = dt.Columns[j].ColumnName;
                string strValue = drc[i][j].ToString();
                Type type = dt.Columns[j].DataType;
                jsonString.Append(""" + strKey + "":");
                strValue = StringFormat(strValue, type);
                if (j < dt.Columns.Count - 1)
                {
                    jsonString.Append(strValue + ",");
                }
                else
                {
                    jsonString.Append(strValue);
                }
            }
            jsonString.Append("},");
        }
        jsonString.Remove(jsonString.Length - 1, 1);
        jsonString.Append("]");
        return jsonString.ToString();
    }
    ///
    /// 格式化字符型、日期型、布尔型
    ///
    ///
    ///
    ///
    private static string StringFormat(string str, Type type)
    {
        if (type == typeof(string))
        {
            str = String2Json(str);
            str = """ + str + """;
        }
        else if (type == typeof(DateTime))
        {
            str = """ + str + """;
        }
        else if (type == typeof(bool))
        {
            str = str.ToLower();
        }
        else if (type != typeof(string) && string.IsNullOrEmpty(str))
        {
            str = """ + str + """;
        }
        return str;
    }
    ///
    /// 过滤特殊字符
    ///
    /// 字符串
    /// json字符串
    private static string String2Json(String s)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.Length; i++)
        {
            char c = s.ToCharArray()[i];
            switch (c)
            {
                case '"':
                    sb.Append("\""); break;
                case '\':
                    sb.Append("\\"); break;
                case '/':
                    sb.Append("\/"); break;
                case 'b':
                    sb.Append("\b"); break;
                case 'f':
                    sb.Append("\f"); break;
                case 'n':
                    sb.Append("\n"); break;
                case 'r':
                    sb.Append("\r"); break;
                case 't':
                    sb.Append("\t"); break;
                default:
                    sb.Append(c); break;
            }
        }
        return sb.ToString();
    }

   

 实例二:
 

代码如下:

 public static string CreateJsonParameters(DataTable dt)
        {
            /**//**/
            /**//* /****************************************************************************
          * Without goingin to the depth of the functioning of this Method, i will try to give an overview
          * As soon as this method gets a DataTable it starts to convert it into JSON String,
          * it takes each row and in each row it grabs the cell name and its data.
          * This kind of JSON is very usefull when developer have to have Column name of the .
          * Values Can be Access on clien in this way. OBJ.HEAD[0].
          * NOTE: One negative point. by this method user will not be able to call any cell by its index.
         * *************************************************************************/
            StringBuilder JsonString = new StringBuilder();
            //Exception Handling       
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append(""T_blog":[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + """ + dt.Rows[i][j].ToString() + "",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + """ + dt.Rows[i][j].ToString() + """);
                        }
                    }
                    /**//**/
                    /**//*end Of String*/
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }
 

效果:
{"T_blog":
  [
   {"id":"14","title":"北京奥运开幕式","addtime":"2008-08-08"},
   {"id":"15","title":"网络文化","addtime":"2008-09-12"},
   {"id":"17","title":"北京下雨了","addtime":"2008-09-19"},
   {"id":"21","title":"深圳地铁通了","addtime":"2008-09-25"}
  ]
}

实例三:

代码如下:

///
    /// 将一个数据表转换成一个JSON字符串,在客户端可以直接转换成二维数组。
    ///
    /// 需要转换的表。
    ///
    public static string DataTableToJson(DataTable source)
    {
        if (source.Rows.Count == 0)
            return "";
        StringBuilder sb = new StringBuilder("[");
        foreach (DataRow row in source.Rows)
        {
            sb.Append("[");
            for (int i = 0; i < source.Columns.Count; i++)
            {
                sb.Append('"' + row[i].ToString() + "",");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("],");
        }
        sb.Remove(sb.Length - 1, 1);
        sb.Append("]");
        return sb.ToString();
    }


    ///
    /// 反回JSON数据到前台
    ///
    /// 数据表
    /// JSON字符串
    public string CreateJsonParameters(DataTable dt)
    {
        StringBuilder JsonString = new StringBuilder();
        //Exception Handling       
        if (dt != null && dt.Rows.Count > 0)
        {
            JsonString.Append("{ ");
            JsonString.Append(""TableInfo":[ ");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                JsonString.Append("{ ");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j < dt.Columns.Count - 1)
                    {
                        JsonString.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + """ + dt.Rows[i][j].ToString() + "",");
                    }
                    else if (j == dt.Columns.Count - 1)
                    {
                        JsonString.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + """ + dt.Rows[i][j].ToString() + """);
                    }
                }
                /**/
                /*end Of String*/
                if (i == dt.Rows.Count - 1)
                {
                    JsonString.Append("} ");
                }
                else
                {
                    JsonString.Append("}, ");
                }
            }
            JsonString.Append("]}");
            return JsonString.ToString();
        }
        else
        {
            return null;
        }
    }

实例四:

代码如下:

public class DataTableConvertJson
    {

        #region dataTable转换成Json格式
        ///  
        /// dataTable转换成Json格式 
        ///  
        ///  
        ///  
        public static string DataTable2Json(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{"");
            jsonBuilder.Append(dt.TableName);
            jsonBuilder.Append("":[");
            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);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        #endregion dataTable转换成Json格式
        #region DataSet转换成Json格式
        ///  
        /// DataSet转换成Json格式 
        ///  
        /// DataSet
        ///  
        public static string Dataset2Json(DataSet ds)
        {
            StringBuilder json = new StringBuilder();

            foreach (DataTable dt in ds.Tables)
            {
                json.Append("{"");
                json.Append(dt.TableName);
                json.Append("":");
                json.Append(DataTable2Json(dt));
                json.Append("}");
            } return json.ToString();
        }
        #endregion

        ///
        /// Msdn
        ///
        ///
        ///
        ///
        public static string DataTableToJson(string jsonName, DataTable dt)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("{"" + jsonName + "":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Json.Append(""" + dt.Columns[j].ColumnName.ToString() + "":"" + dt.Rows[i][j].ToString() + """);
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
    }

实例五:

代码如下:

#region  DataTable 转换为Json字符串实例方法
///
/// GetClassTypeJosn 的摘要说明
///
public class GetClassTypeJosn : IHttpHandler
{
    ///
    /// 文件名:DataTable 和Json 字符串互转
    /// 版权所有:Copyright (C) Create Family Wealth liangjw
    /// 创建标示:2013-08-03
    ///
    //用法说明实例
     public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        context.Response.Charset = "utf-8";
        HttpRequest req = context.Request;
        string method = req["method"].ToStr().ToLower();


       //获取合同明细列表  DataTable 转换为Json字符串
        if (method == "txtdate")
        {
            string json = "";
            BO.MakeContractMx bll = new MakeContractMx();
            DataSet ds = bll.GetDataTable();
            if (ds.Tables.Count > 0)
            {
                json =ToJson(ds.Tables[0]);
            }
            context.Response.Write(json);
            return;
        }

    }

   public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

   #endregion

    #region Json字符串转换为DataTable 实例方法

    public DataTable JsonToDataTable(json)
    {
       DataTable  dt= ToDataTable(json);
         return dt;
    }

   #endregion

    #region DataTable 转换为Json 字符串
    ///
    /// DataTable 对象 转换为Json 字符串
    ///
    ///
    ///
    public static string ToJson(this DataTable dt)
    {
        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
        javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
        ArrayList arrayList = new ArrayList();
        foreach (DataRow dataRow in dt.Rows)
        {
            Dictionary dictionary = new Dictionary();  //实例化一个参数集合
            foreach (DataColumn dataColumn in dt.Columns)
            {
                dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToStr());
            }
            arrayList.Add(dictionary); //ArrayList集合中添加键值
        }

        return javaScriptSerializer.Serialize(arrayList);  //返回一个json字符串
    }
    #endregion

    #region Json 字符串 转换为 DataTable数据集合
    ///
    /// Json 字符串 转换为 DataTable数据集合
    ///
    ///
    ///
    public static DataTable ToDataTable(this string json)
    {
        DataTable dataTable = new DataTable();  //实例化
        DataTable result;
        try
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
            ArrayList arrayList = javaScriptSerializer.Deserialize(json);
            if (arrayList.Count > 0)
            {
                foreach (Dictionary dictionary in arrayList)
                {
                    if (dictionary.Keys.Count() == 0)
                    {
                        result = dataTable;
                        return result;
                    }
                    if (dataTable.Columns.Count == 0)
                    {
                        foreach (string current in dictionary.Keys)
                        {
                            dataTable.Columns.Add(current, dictionary[current].GetType());
                        }
                    }
                    DataRow dataRow = dataTable.NewRow();
                    foreach (string current in dictionary.Keys)
                    {
                        dataRow[current] = dictionary[current];
                    }

                    dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                }
            }
        }
        catch
        {
        }
        result = dataTable;
        return result;
    }
    #endregion

    #region 转换为string字符串类型
    ///
    ///  转换为string字符串类型
    ///
    /// 获取需要转换的值
    /// 需要格式化的位数
    /// 返回一个新的字符串
    public static string ToStr(this object s, string format = "")
    {
        string result = "";
        try
        {
            if (format == "")
            {
                result = s.ToString();
            }
            else
            {
                result = string.Format("{0:" + format + "}", s);
            }
        }
        catch
        {
        }
        return result;
    }
   #endregion


    
 
 

您可能感兴趣的文章:

  • C#实现Datatable排序的方法
  • c# dataTable 合并两个列到一个新列中的简单实例
  • c#将list类型转换成DataTable方法示例
  • C# datatable 不能通过已删除的行访问该行的信息处理方法
  • asp.net(c#版)添加DataRow数据列到DataTable控件
  • C# DataTable 转换为 实体类对象实例
  • c#的datatable转list示例
  • C#中DataTable删除行的方法分析
  • c#中合并DataTable重复行的值
  • c#数据绑定之删除datatable数据示例
  • C#中datatable序列化与反序列化实例分析
  • C#获取变更过的DataTable记录的实现方法
  • C#操作EXCEL DataTable转换的实例代码
  • C#对DataTable里数据排序的方法
  • c# 如何将RadioButton与DataTable数据进行绑定
  • C#中csv文件与DataTable互相导入处理实例解析
  • c# DataTable与不同结构实体类转换的方法实例
  • C#中DataTable排序、检索、合并等操作实例
  • C#使用DataSet Datatable更新数据库的三种实现方法
  • c# 委托反射 DataTable转换为实体集的方法
  • asp.net实例代码之添加DataColumn到DataTable控件中
  • .Net读取Excel 返回DataTable实例代码
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • Delete与Remove删除Datatable行的区别
  • DataSet与DataTable的区别示例介绍
  • datatable去掉重复行的方法
  • jquery转化Datatable为json数据的例子
  • DataSet、DataTable、DataRow区别详解
  • datatable行转列示例分享
  • 比较2个datatable内容是否相同的方法
  • npoi2.0将datatable对象转换为excel2007示例
  • Asp.net中DataTable导出到Excel的实现代码
  • sqlserver合并DataTable并排除重复数据的通用方法分享
  • c#.net 读取Excel数据到DataTable中的代码
  • 将DataTable转换成List<T>实现思路及示例代码
  • c#使用委托反射将DataTable转换为实体集的代码
  • c#中利用委托反射将DataTable转换为实体集的代码
  • jquery datatable后台封装数据示例代码
  • C#如何将DataTable导出到Excel解决方案
  • C#中的DataSet、string、DataTable、对象转换成Json的实现代码
  • SqlServer参数化查询之where in和like实现之xml和DataTable传参介绍
  • viewstate和datatable动态录入数据示例
  • datatable生成excel和excel插入图片示例详解


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3