C#、结构、JSON

7lrncoxx  于 2023-01-22  发布在  C#
关注(0)|答案(1)|浏览(140)

我有一些JSON文件和结构。在静态void Initialization()中,我想把json文件中的信息放到Data[i]中。我该怎么做呢?

private static Student[] Data = new Student[99];
        struct Student
        {
            public int Id;
            public string FullName;
            public DateTime BirthdayDate;
            public string Institute;
            public string Group;
            public string Course;
            public double AvgMark;
            public string form_ed;
            public string lvl_ed;
            public int zadolzh;

            public Student(int Id, string FullName, DateTime BirthdayDate, string Institute, string Group, string Course, double AvgMark, string form_ed, string lvl_ed, int zadolzh)
            {
                this.Id = Id;
                this.FullName = FullName;
                this.BirthdayDate = BirthdayDate;
                this.Institute = Institute;
                this.Group = Group;
                this.Course = Course;
                this.AvgMark = AvgMark;
                this.form_ed = form_ed;
                this.lvl_ed = lvl_ed;
                this.zadolzh = zadolzh;
            } 
        }
static void Initialization()
{
        
}
c3frrgcw

c3frrgcw1#

你可以使用JSON.Net和类似的代码。代替student,你可以把它赋给你的数组项。

string json = File.ReadAllText("test.txt");
var student = JsonConvert.DeserializeObject<Student>(json);

我假设您的JSON是:

{
  "id": 0,
  "fullName": null,
  "birthdayDate": "0001-01-01T00:00:00",
  "institute": null,
  "group": null,
  "course": null,
  "avgMark": 0.0,
  "form_ed": null,
  "lvl_ed": null,
  "zadolzh": 0
}

更优化的解决方案是使用下面的JSON并将其反序列化为student[]

[{
    "id": 0,
    "fullName": null,
    "birthdayDate": "0001-01-01T00:00:00",
    "institute": null,
    "group": null,
    "course": null,
    "avgMark": 0.0,
    "form_ed": null,
    "lvl_ed": null,
    "zadolzh": 0
},
{
    "id": 1,
    "fullName": null,
    "birthdayDate": "0001-01-01T00:00:00",
    "institute": null,
    "group": null,
    "course": null,
    "avgMark": 0.0,
    "form_ed": null,
    "lvl_ed": null,
    "zadolzh": 0
}]
string json = File.ReadAllText("test.txt");
var students = JsonConvert.DeserializeObject<Student[]>(json);

正如Jon Skeet所建议的,最好在这里使用class代替struct,您只需要将struct关键字替换为class

相关问题