C#中把Datatable轉換為Json的5個代碼執行個體

來源:互聯網
上載者:User
執行個體一:

/// <summary>         /// Datatable轉換為Json         /// </summary>        /// <param name="table">Datatable對象</param>         /// <returns>Json字串</returns>         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();    }    /// <summary>    /// 格式化字元型、日期型、布爾型    /// </summary>    /// <param name="str"></param>    /// <param name="type"></param>    /// <returns></returns>    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;    }    /// <summary>    /// 過濾特殊字元    /// </summary>    /// <param name="s">字串</param>    /// <returns>json字串</returns>    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].<ColumnName>          * 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"}
]
}

執行個體三:

/// <summary>    /// 將一個資料錶轉換成一個JSON字串,在用戶端可以直接轉換成二維數組。    /// </summary>    /// <param name="source">需要轉換的表。</param>    /// <returns></returns>    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();    }    /// <summary>    /// 反回JSON資料到前台    /// </summary>    /// <param name="dt">資料表</param>    /// <returns>JSON字串</returns>    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格式        /// <summary>          /// dataTable轉換成Json格式          /// </summary>          /// <param name="dt"></param>          /// <returns></returns>          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格式        /// <summary>          /// DataSet轉換成Json格式          /// </summary>          /// <param name="ds">DataSet</param>         /// <returns></returns>          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        /// <summary>        /// Msdn        /// </summary>        /// <param name="jsonName"></param>        /// <param name="dt"></param>        /// <returns></returns>        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字串執行個體方法/// <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
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.