C# 實現Json 序列化和反序列化功能
阿新 • • 發佈:2019-01-24
1、新建一個 JSON 類,實現如下所示程式碼:
/* * * 表示層的輔助類 * * 功能:JSON序列化和反序列化 * 作者:凌霜殘血 * */ public class JSON { public static string DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss"; public static string Encode(object o) { if (o == null || o.ToString() == "null") return null; if (o != null && (o.GetType() == typeof(String) || o.GetType() == typeof(string))) { return o.ToString(); } //不隨機排序的Hashtable if (o.GetType() == typeof(NoSortHashtable)) { NoSortHashtable ht = (NoSortHashtable)o; string json = "{"; foreach (string key in ht.Keys) { object value = ht[key]; if (value.GetType() == typeof(String) || value.GetType() == typeof(string)) json += "\"" + key + "\":\"" + value.ToString() + "\","; //字串 else json += "\"" + key + "\":" + value.ToString().ToLower() + ","; //非字串,如整型或布林型 } json = json.Substring(0, json.Length - 1); //去掉最後一個逗號 json += "}"; return json; } IsoDateTimeConverter dt = new IsoDateTimeConverter(); dt.DateTimeFormat = DateTimeFormat; return JsonConvert.SerializeObject(o, dt); } public static object Decode(string json) { if (String.IsNullOrEmpty(json)) return ""; object o = JsonConvert.DeserializeObject(json); if (o.GetType() == typeof(String) || o.GetType() == typeof(string)) { o = JsonConvert.DeserializeObject(o.ToString()); } object v = toObject(o); return v; } public static object Decode(string json, Type type) { return JsonConvert.DeserializeObject(json, type); } private static object toObject(object o) { if (o == null) return null; if (o.GetType() == typeof(string)) { //判斷是否符合2010-09-02T10:00:00的格式 string s = o.ToString(); if (s.Length == 19 && s[10] == 'T' && s[4] == '-' && s[13] == ':') { o = System.Convert.ToDateTime(o); } } else if (o is JObject) { JObject jo = o as JObject; Hashtable h = new Hashtable(); foreach (KeyValuePair<string, JToken> entry in jo) { h[entry.Key] = toObject(entry.Value); } o = h; } else if (o is IList) { ArrayList list = new ArrayList(); list.AddRange((o as IList)); int i = 0, l = list.Count; for (; i < l; i++) { list[i] = toObject(list[i]); } o = list; } else if (typeof(JValue) == o.GetType()) { JValue v = (JValue)o; o = toObject(v.Value); } else { } return o; } }
2、實現不隨機排序的 Hashtable,新建 NoSortHashtable.cs 類,實現程式碼如下:
/* * * 表示層的輔助類 * * 功能:實現Hashtable不隨機進行排序 * 作者:王武 * */ public class NoSortHashtable : Hashtable { private ArrayList keys = new ArrayList(); //藉助ArrayList來指定順序,從而避免使用Hashtable原有的隨機順序 //建構函式 public NoSortHashtable() { } //新增元素 public override void Add(object key, object value) { base.Add(key, value); keys.Add(key); } //泛型的key集合 public override ICollection Keys { get { return keys; } } //清除所有元素 public override void Clear() { base.Clear(); keys.Clear(); } //刪除一個元素 public override void Remove(object key) { base.Remove(key); keys.Remove(key); } public override IDictionaryEnumerator GetEnumerator() { return base.GetEnumerator(); } }
如此,可以將任何型別資料轉化成Json字串;注意兩個類的引用:
那麼 如何使用這個JSON類呢,如下所示:
protected void Page_Load(object sender, EventArgs e) { DataTable tbl = new DataTable(); tbl.Columns.Add("id1", typeof(Int32)); //Id tbl.Columns.Add("text1", typeof(String)); //名稱 tbl.Columns.Add("seq1", typeof(String)); //編號 List<Models.AlarmConfig> models = new List<Models.AlarmConfig>(); Models.AlarmConfig m1 = new Models.AlarmConfig(); m1.AlarmTypeId = 1; m1.AlarmTypeName = "張三"; Models.AlarmConfig m2 = new Models.AlarmConfig(); m2.AlarmTypeId = 2; m2.AlarmTypeName = "李四"; Models.AlarmConfig m3 = new Models.AlarmConfig(); m3.AlarmTypeId = 3; m3.AlarmTypeName = "王者"; models.Add(m1); models.Add(m2); models.Add(m3); foreach (Models.AlarmConfig model in models) { DataRow row = tbl.NewRow(); row["id"] = model.AlarmTypeId; row["text"] = model.AlarmTypeName; tbl.Rows.Add(row); } string json = JSON.Encode(tbl); Response.Write(json); }
這樣只要在前端做一個Json字串接收就可以了,執行效果如下:
將Dll檔案拷貝到bin資料夾下,新增外部引用即可;