【问题标题】:C#, Structure, JSONC#,结构,JSON
【发布时间】:2021-12-29 02:06:05
【问题描述】:

我有一些 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()
{
        
}


【问题讨论】:

  • Json.NET 将是最简单的方法
  • 这里使用类而不是结构会更传统。
  • 在你的初始化方法中,循环你的json文件,反序列化每个文件并将返回的学生对象放入学生数组中。
  • 请显示你的json

标签: c# json database structure


【解决方案1】:

您可以使用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即可。

【讨论】:

    猜你喜欢
    • 2011-11-15
    • 2016-01-05
    • 2011-10-05
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多