C#字典序列化為Json字符串並寫入文件


using System.Text.Json;
using System.IO;
using System.Text;

        public static Dictionary<Byte, Command> Commandss = new Dictionary<Byte, Command>();
        public static string fileName = "temp";

        public class Command
        {
            public Byte command { get; set; }
            public string name { get; set; }
            public string datatype { get; set; }
            public UInt16 datalength { get; set; }
            public string dataformat { get; set; }
            public Double coefficient { get; set; }
            public Double minValue { get; set; }
            public Double maxValue { get; set; }
            public Double defValue { get; set; }
            public string unit { get; set; }
            public string checktype { get; set; }
            public bool showState { get; set; }
            public Double Value { get; set; }
        }

        private void writeFile()
        {
            string jsonstr = JsonSerializer.Serialize(Commandss);
            string path = System.IO.Directory.GetCurrentDirectory() + fileName + "pmb";
            if (!File.Exists(path))
            {
                File.WriteAllText(path, jsonstr, Encoding.UTF8);
            }

        }
        private void readFile()
        {
            string path = System.IO.Directory.GetCurrentDirectory() + fileName + "pmb";
            string jsonstr = File.ReadAllText(path);

            Commandss = JsonSerializer.Deserialize<Dictionary<Byte, Command>>(jsonstr);

        }

使用using System.Text.Json;前需安裝對應的庫文件

 

 打開NuGet控制台,輸入:dotnet add package System.Text.Json --version 5.0.1

參考:

https://www.nuget.org/packages/System.Text.Json

https://docs.microsoft.com/zh-cn/dotnet/standard/serialization/system-text-json-overview

https://docs.microsoft.com/zh-cn/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0

遺留問題:

1.最早嘗試的是對List(元素為結構體)進行序列化,序列化后數據全部丟失,原因未找到

2.轉為Json字符串后,中文字符被轉為"\u6253\u5F00/\u5173\u95ED\u7535\u6E90\u4E3B\u8DEF\u8F93\u51FA"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM