【轉載】C#工具類:Json操作幫助類
阿新 • • 發佈:2019-03-22
哈希表 封裝 bst repl 遇到 json serial 轉載 res
Json序列化和反序列化在程序開發中時常會遇到,在C#中可以使用很多種方法實現對數據的Json序列化和反序列化,封裝一個Json操作工具類來簡化相應的操作,該工具類中包含以下功能:對象轉JSON、數據表轉鍵值對集合、數據集轉鍵值對數組字典 、數據表轉JSON、JSON文本轉對象(泛型方法)、將JSON文本轉換為數據表數據、將JSON文本轉換成數據行、將json轉換為DataTable等。
封裝後的工具幫助類如下:
/// <summary> /// JSON幫助類 /// </summary> public class JsonHelper {/// <summary> /// 對象轉JSON /// </summary> /// <param name="obj">對象</param> /// <returns>JSON格式的字符串</returns> public static string ObjectToJSON(object obj) { JavaScriptSerializer jss = new JavaScriptSerializer();try { byte[] b = Encoding.UTF8.GetBytes(jss.Serialize(obj)); return Encoding.UTF8.GetString(b); } catch (Exception ex) { throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message); } }/// <summary> /// 數據表轉鍵值對集合 /// 把DataTable轉成 List集合, 存每一行 /// 集合中放的是鍵值對字典,存每一列 /// </summary> /// <param name="dt">數據表</param> /// <returns>哈希表數組</returns> public static List<Dictionary<string, object>> DataTableToList(DataTable dt) { List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); foreach (DataRow dr in dt.Rows) { Dictionary<string, object> dic = new Dictionary<string, object>(); foreach (DataColumn dc in dt.Columns) { dic.Add(dc.ColumnName, dr[dc.ColumnName]); } list.Add(dic); } return list; } /// <summary> /// 數據集轉鍵值對數組字典 /// </summary> /// <param name="dataSet">數據集</param> /// <returns>鍵值對數組字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds) { Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>(); foreach (DataTable dt in ds.Tables) result.Add(dt.TableName, DataTableToList(dt)); return result; } /// <summary> /// 數據表轉JSON /// </summary> /// <param name="dataTable">數據表</param> /// <returns>JSON字符串</returns> public static string DataTableToJSON(DataTable dt) { return ObjectToJSON(DataTableToList(dt)); } /// <summary> /// JSON文本轉對象,泛型方法 /// </summary> /// <typeparam name="T">類型</typeparam> /// <param name="jsonText">JSON文本</param> /// <returns>指定類型的對象</returns> public static T JSONToObject<T>(string jsonText) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Deserialize<T>(jsonText); } catch (Exception ex) { throw new Exception("JSONHelper.JSONToObject(): " + ex.Message); } } /// <summary> /// 將JSON文本轉換為數據表數據 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>數據表字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText) { return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText); } /// <summary> /// 將JSON文本轉換成數據行 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>數據行的字典</returns> public static Dictionary<string, object> DataRowFromJSON(string jsonText) { return JSONToObject<Dictionary<string, object>>(jsonText); } /// <summary> /// 將json轉換為DataTable /// </summary> /// <param name="strJson">得到的json</param> /// <returns></returns> public static DataTable JsonToDataTable(string strJson) { //轉換json格式 strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString(); //取出表名 var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase); string strName = rg.Match(strJson).Value; DataTable tb = null; //去除表名 strJson = strJson.Substring(strJson.IndexOf("[") + 1); strJson = strJson.Substring(0, strJson.IndexOf("]")); //獲取數據 rg = new Regex(@"(?<={)[^}]+(?=})"); MatchCollection mc = rg.Matches(strJson); for (int i = 0; i < mc.Count; i++) { string strRow = mc[i].Value; string[] strRows = strRow.Split(‘*‘); //創建表 if (tb == null) { tb = new DataTable(); tb.TableName = strName; foreach (string str in strRows) { var dc = new DataColumn(); string[] strCell = str.Split(‘#‘); if (strCell[0].Substring(0, 1) == "\"") { int a = strCell[0].Length; dc.ColumnName = strCell[0].Substring(1, a - 2); } else { dc.ColumnName = strCell[0]; } tb.Columns.Add(dc); } tb.AcceptChanges(); } //增加內容 DataRow dr = tb.NewRow(); for (int r = 0; r < strRows.Length; r++) { dr[r] = strRows[r].Split(‘#‘)[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", ""); } tb.Rows.Add(dr); tb.AcceptChanges(); } return tb; } }
備註:原文轉載自C#工具類:Json操作幫助類_IT技術小趣屋。
【轉載】C#工具類:Json操作幫助類