說明:Dictionary對象本身不支持序列化和反序列化,需要定義一個繼承自Dictionary, IXmlSerializable類的自定義類來實現該功能。感覺完全可以把這樣的類封裝到C#庫中,很具有通用性嘛,至今沒有遇到不能用的情況的說,或許出於其他方面的考慮microsoft才沒有這么做。
這里說的是字典的鍵值是自定義類的情況,其他情況不在討論范圍,所使用的Newtonsoft.Json.dll。
閑話少說,直接上代碼。
自定義類:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RedisTest.Test { [Serializable] public class TestClass { public string Name = ""; public TestClass(string n) { Name = n; } public override bool Equals(object obj) { TestClass other = obj as TestClass; if (other == null) return false; if (!base.GetType().Equals(obj.GetType())) return false; return (this.Name.Equals(other.Name)); } public override int GetHashCode() { return Name.GetHashCode(); } public static explicit operator TestClass(string jsonString) { return Newtonsoft.Json.JsonConvert.DeserializeObject<TestClass>(jsonString); } public override string ToString() { return Newtonsoft.Json.JsonConvert.SerializeObject(this); } } }
測試代表:
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RedisTest.Test { class Program { static void Main(string[] args) { Dictionary<TestClass, int> dic = new Dictionary<TestClass, int>(); TestClass c = new TestClass("c0"); dic.Add(c, 0); TestClass c1 = new TestClass("c1"); dic.Add(c1, 1); TestClass c2 = new TestClass("c2"); dic.Add(c2, 2); TestClass c3 = new TestClass("c3"); dic.Add(c3, 3); string json = JsonConvert.SerializeObject(dic, Formatting.Indented); Console.WriteLine(json); Dictionary<TestClass, int> dic1 = JsonConvert.DeserializeObject<Dictionary<TestClass, int>>(json); } } }
其中重要的是:
public static explicit operator TestClass(string jsonString) { return Newtonsoft.Json.JsonConvert.DeserializeObject<TestClass>(jsonString); } public override string ToString() { return Newtonsoft.Json.JsonConvert.SerializeObject(this); }