c# Json Dictionary序列化和反序列化

mac2022-06-30  21

说明: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); }

 

转载于:https://www.cnblogs.com/zoro-zero/p/6184159.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)