C# 如何在Initialization方法中将JSON数据写入Student结构体数组Data
C# 实现JSON内容赋值到Student结构体数组的方案
前置依赖
- 优先使用.NET 自带的
System.Text.Json库(.NET Core 3.0 / .NET 5+ 原生支持,无需额外安装NuGet包),如果使用.NET Framework可选择Newtonsoft.Json(Json.NET)实现
准备匹配结构的JSON文件
你的JSON文件字段需要和Student结构体字段对应,示例格式如下(文件路径示例:
./students.json)
[ { "Id": 1, "FullName": "Иванов Иван Иванович", "BirthdayDate": "2000-05-15", "Institute": "计算机学院", "Group": "CS-202", "Course": "大三", "AvgMark": 4.7, "form_ed": "全日制", "lvl_ed": "本科", "zadolzh": 0 }, { "Id": 2, "FullName": "Петров Петр Петрович", "BirthdayDate": "2001-02-20", "Institute": "经管学院", "Group": "MAN-101", "Course": "大二", "AvgMark": 4.2, "form_ed": "全日制", "lvl_ed": "本科", "zadolzh": 1 } ]
代码实现
首先添加需要的命名空间引用:
using System.IO; using System.Text.Json;
然后完成Initialization方法的编写:
static void Initialization() { // 替换为你的JSON文件实际存储路径 string jsonFilePath = @"./students.json"; // 读取JSON文件全部文本内容 string jsonContent = File.ReadAllText(jsonFilePath); // 配置反序列化规则 var jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, // 忽略JSON字段和结构体字段的大小写差异 IncludeFields = true, // 开启公共字段的序列化/反序列化支持 DateFormatString = "yyyy-MM-dd" // 可根据你JSON里的实际日期格式调整 }; // 将JSON反序列化为Student数组 Student?[]? deserializedStudents = JsonSerializer.Deserialize<Student?[]>(jsonContent, jsonOptions); // 赋值到全局Data数组,避免超出预设的99长度限制 if (deserializedStudents != null) { int copyLength = Math.Min(deserializedStudents.Length, Data.Length); Array.Copy(deserializedStudents, Data, copyLength); } }
可选:Newtonsoft.Json版本实现
如果你的项目使用.NET Framework,可安装Newtonsoft.Json NuGet包后使用以下实现:
using System.IO; using Newtonsoft.Json; static void Initialization() { string jsonFilePath = @"./students.json"; string jsonContent = File.ReadAllText(jsonFilePath); Student[] deserializedStudents = JsonConvert.DeserializeObject<Student[]>(jsonContent); if (deserializedStudents != null) { int copyLength = Math.Min(deserializedStudents.Length, Data.Length); Array.Copy(deserializedStudents, Data, copyLength); } }
内容的提问来源于stack exchange,提问作者Кирилл Курочкин
相关产品推荐
相关产品推荐

