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

说明: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);
        }
复制代码

 

posted @   大空白纸  阅读(17349)  评论(1编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示