C#-Json文件的读写

坚持记录实属不易,希望友善多金的码友能够随手点一个赞。
共同创建氛围更加良好的开发者社区!
谢谢~

命名空间

using Newtonsoft.Json;

读取Json

核心代码

                //核心代码
                    using (StreamReader file = File.OpenText(filePath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                       var ret = (类型)serializer.Deserialize(file, typeof(类型));
                    }

示例

        Dictionary<string, double> LoadDictionaryFromFile()
        {
            Dictionary<string, double> ret = new Dictionary<string, double>();
            try
            {
                if (!Directory.Exists(folderPath))
                {
                    //检查文件目录是否存在
                    Directory.CreateDirectory(folderPath);
                }

                var filePath = Path.Combine(folderPath, FileName);
                if (!File.Exists(filePath))
                {
                    File.Create(filePath);
                }
                else
                {
                //核心代码
                    using (StreamReader file = File.OpenText(filePath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        ret = (Dictionary<string, double>)serializer.Deserialize(file, typeof(Dictionary<string, double>));
                    }
                }
            }
            catch (Exception ex)
            {
                MainDeviceProvider.Instance.Logger.Error("解析出现错误!",ex);
            }
            return ret;
        }

写入Json

核心代码


                var filePath = Path.Combine(folderPath, FileName);
                string data = JsonConvert.SerializeObject(dataDictionary, Formatting.Indented);
                File.WriteAllText(filePath, data);

示例

void SaveDataToFile()
        {
            try
            {
                var filePath = Path.Combine(folderPath, FileName);
                string data = JsonConvert.SerializeObject(dataDictionary, Formatting.Indented);
                File.WriteAllText(filePath, data);
            }
            catch(Exception ex)
            {
                MainDeviceProvider.Instance.Logger.Error("写入出现错误!", ex);
            }
        }
C#中,可以使用Json.NET库来读写JSON文件。首先,你需要在项目中引用Json.NET库。然后,你可以通过以下方法读取JSON文件和将数据写入JSON文件: 1. 读取JSON文件: - 首先,使用`File.Exists`方法检查文件是否存在。 - 然后,使用`File.ReadAllText`方法读取文件内容,并将其存储为一个字符串。 - 使用`JsonConvert.DeserializeObject<T>`方法将字符串反序列化为指定的类型(在这个例子中是`ReadJson`类)。 2. 将数据写入JSON文件: - 你可以创建一个用于存储数据的类(在这个例子中是`ReadJson`类)。 - 将数据赋值给该类的属性。 - 使用`JsonConvert.SerializeObject`方法将类对象序列化为JSON字符串。 - 使用`File.WriteAllText`方法将JSON字符串写入文件。 以下是一个示例代码,展示了如何读取和写入JSON文件: ```csharp // 读取JSON文件 private void ReadJsonFile(string fileName) { if (File.Exists(fileName)) { string json = File.ReadAllText(fileName); ReadJson data = JsonConvert.DeserializeObject<ReadJson>(json); // 对读取到的数据进行操作 // 这里是将数据展示在listBox1中 listBox1.Items.Add(AppDomain.CurrentDomain.BaseDirectory); this.y1_value = data.y1_value; this.y2_value = data.y2_value; this.y3_value = data.y3_value; this.y4_value = data.y4_value; this.y5_value = data.y5_value; this.y6_value = data.y6_value; this.y7_value = data.y7_value; this.y8_value = data.y8_value; this.y9_value = data.y9_value; List<List<int>> yValues = new List<List<int>>() { y1_value, y2_value, y3_value, y4_value, y5_value, y6_value, y7_value, y8_value, y9_value }; for (int i = 0; i < yValues.Count; i++) { string prefix = $"y{i + 1}"; string line = string.Join(" ", yValues[i]); listBox1.Items.Add($"{prefix}: {line}"); } } } // 写入JSON文件 private void WriteJsonFile(string fileName) { ReadJson data = new ReadJson() { y1_value = new List<int>() { 1, 2, 3 }, y2_value = new List<int>() { 4, 5, 6 }, y3_value = new List<int>() { 7, 8, 9 }, // 其他数据... }; string json = JsonConvert.SerializeObject(data); File.WriteAllText(fileName, json); } ``` 请注意,你需要根据自己的需求调整代码中的类和属性名称。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默九思

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值