C# Winform序列化和反序列化

发布于:2024-08-12 ⋅ 阅读:(132) ⋅ 点赞:(0)

在NET Framework 4.7.2中不能用Newtonsoft.Json进行序列化和反序列化,为解决此问题,采用System.Text.Json进行序列化,注意要添加System.Memory的引用。
1、创建测试类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoTestClientApp.Models
{
    public class CmdNode
    {
        public string Name { get; set; } = string.Empty;
        public int CmdWord { get; set; } = 0;
        public int Direction { get; set; } = 0;
        public object Data { get; set; } = 0;
        public bool Compare(CmdNode other)
        {
            if (Name.Equals(other.Name) && CmdWord == other.CmdWord && Direction == other.Direction && Data.Equals(other.Data))
            {
                return true;
            }
            return false;
        }
    }
}

2、应用测试

//实例化类并赋值
            CmdNode cmdNode = new CmdNode();
            cmdNode.Name = "序列化测试";
            cmdNode.CmdWord = 0x10;
            cmdNode.Direction = 1;
            List<string> list = new List<string>();
            list.Add("12");
            list.Add("34");
            cmdNode.Data = list;
            //实例序列化
            string str = System.Text.Json.JsonSerializer.Serialize(cmdNode);
            Console.WriteLine(str);
            //实例反序列化
            CmdNode cmdNode1 = System.Text.Json.JsonSerializer.Deserialize<CmdNode>(str);
            bool flag = cmdNode1.Compare(cmdNode);
            Console.WriteLine($"粗略比较结果:{flag}");

3、运行结果
在这里插入图片描述
在这里插入图片描述
4、问题分析
反序列化后不相等的原因在于对象类型比较的不完善。


网站公告

今日签到

点亮在社区的每一天
去签到