• 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字符串后,中文字符被转为"u6253u5F00/u5173u95EDu7535u6E90u4E3Bu8DEFu8F93u51FA"

    转载请注明出处:https://www.cnblogs.com/lei-zi/
  • 相关阅读:
    mysql使用命令备份和导入导出数据
    jmeter中json提取器提取多个参数给下游接口传参
    jmeter使用正则提取器返回多个参数给下游接口入参使用
    linux下分布式部署jmeter
    使用java远程启动jmeter服务报错,报错内容:Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
    Java中看今天是星期几,礼拜几
    java读取xml文件的四种方法
    Oracle 恢复删除的表
    重启Oracle命令
    Android 资源
  • 原文地址:https://www.cnblogs.com/lei-zi/p/14474741.html
Copyright © 2020-2023  润新知