C# 实现Json文件读写_c# 读取json

JSON是一种轻量级的数据交换格式。它基于 ECMAScript的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

首先在项目中引用第三方库:Newtonsoft.Json
在这里插入图片描述
编写模型类,定义Json结构

//模型类,定义Json结构
    public class BaseModel
    {
        public List<ModelData> list_groupA { get; set; } = new List<ModelData>();
        public List<ModelData> list_groupB { get; set; } = new List<ModelData>();
        public List<ModelData> list_groupC { get; set; } = new List<ModelData>();
    }

    public class ModelData
    {
        public ModelData(int iD, int pointX, int pointY, string groupName)
        {
            ID = iD;
            PointX = pointX;
            PointY = pointY;
            GroupName = groupName;
        }

        public int ID { get; set; }
        public int PointX { get; set; }
        public int PointY { get; set; }
        public string GroupName { get; set; }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

序列化Json字符串,并保存文件

public void SaveToFile(string filePath)
        {
            if (filePath != "")
            {
                List<ModelData> list = new List<ModelData>(100);

                for (int i = 1; i <= 100; i++)
                {
                    if (i < 50)
                    {
                        list.Add(new ModelData(i, 10, 10, "集合A"));
                    }
                    else if (i >= 50 && i < 75)
                    {
                        list.Add(new ModelData(i, 20, 20, "集合B"));
                    }
                    else
                    {
                        list.Add(new ModelData(i, 30, 30, "集合C"));
                    }
                }
                BaseModel model = new BaseModel();
                model.list_groupA = list.Where(x => x.GroupName == "集合A").ToList();
                model.list_groupB = list.Where(x => x.GroupName == "集合B").ToList();
                model.list_groupC = list.Where(x => x.GroupName == "集合C").ToList();
                string json2 = JsonConvert.SerializeObject(model);
                WriteJsonFile(filePath, json2);
            }
        }

        /// <summary>
        /// 将序列化的json字符串内容写入Json文件,并且保存
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="jsonConents">Json内容</param>
        public void WriteJsonFile(string path, string jsonConents)
        {
            try
            {
                File.WriteAllText(path, jsonConents, System.Text.Encoding.UTF8);
                MessageBox.Show("保存成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

如果不需要分组可将序列化对象改为list,即:

string json2 = JsonConvert.SerializeObject(list);
  • 1

读取文本字符串反序列化,获取指定字段值

public void ReadJsonFile(string readFilePath)
        {
            if (File.Exists(readFilePath))
            {
                //获取文件内容
                string readString = File.ReadAllText(readFilePath);
                //反序列化:单组
                /*JArray ja = (JArray)JsonConvert.DeserializeObject(readString);
                int jaCount = ja.Count;
                ja[0]["PinHight"].ToString();*/
                //反序列化
                JObject jo = JsonConvert.DeserializeObject<JObject>(readString);
                int joCount = jo.Count;
                //获取指定位置值
                int str = jo["list_groupA"][0].Value<int>("ID");
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

读取Json文件,更新字段

/// <summary>
        /// 更新字段
        /// </summary>
        /// <param name="fileName"></param>
        public void UpdateJsonFile(string fileName)
        {
            string jsonString = File.ReadAllText(fileName, System.Text.Encoding.UTF8);//读取文件
            JObject jobject = JObject.Parse(jsonString);//解析成json
            jobject["list_student"][0]["ID"] = 111;//替换需要的文件
            string convertString = Convert.ToString(jobject);//将json装换为string
            File.WriteAllText(fileName, convertString, System.Text.Encoding.UTF8);//将内容写进jon文件中
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12