c#常用的Datable转换为json,以及json转换为DataTable操作方法

Posted 山涧清泉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#常用的Datable转换为json,以及json转换为DataTable操作方法相关的知识,希望对你有一定的参考价值。

#region  DataTable 转换为Json字符串实例方法
/// <summary>
/// GetClassTypeJosn 的摘要说明
/// </summary>
public class GetClassTypeJosn : IHttpHandler
{
    /// <summary>
    /// 文件名:DataTable 和Json 字符串互转
    /// 版权所有:Copyright (C) Create Family Wealth liangjw
    /// 创建标示:2013-08-03
    /// </summary> 
    //用法说明实例
     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 字符串
    /// <summary>
    /// DataTable 对象 转换为Json 字符串
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    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<string, object> dictionary = new Dictionary<string, object>();  //实例化一个参数集合
            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数据集合
    /// <summary>
    /// Json 字符串 转换为 DataTable数据集合
    /// </summary>
    /// <param name="json"></param>
    /// <returns></returns>
    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<ArrayList>(json);
            if (arrayList.Count > 0)
            {
                foreach (Dictionary<string, object> dictionary in arrayList)
                {
                    if (dictionary.Keys.Count<string>() == 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字符串类型
    /// <summary>
    ///  转换为string字符串类型
    /// </summary>
    /// <param name="s">获取需要转换的值</param>
    /// <param name="format">需要格式化的位数</param>
    /// <returns>返回一个新的字符串</returns>
    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#常用的Datable转换为json,以及json转换为DataTable操作方法的主要内容,如果未能解决你的问题,请参考以下文章

C#常用方法——json转DataTable集合

将 C# 对象转换为 Json 对象

Unity中基于EPPLUS的Excel转换以及Json数据读取

javascript的JSON对象

Json转换类库

JSON转换为GSON和POJO类