简体   繁体   English

尝试在 C#/JSON 中加载和保存对象

[英]Trying to Load and Save objects in C# / JSON

Section giving difficulties部分给予困难

const string _studentRepositoryPath = @"students.json"; 

        static void Save() {
            using (var file = File.CreateText(_studentRepositoryPath))
        {
            file.WriteAsync(JsonSerializer.Serialize(studentsList));
        }
        }
            static List<Student> Read() {
            return JsonSerializer.Deserialize<List<Student>>(File.ReadAllText(_studentRepositoryPath));
        }
        static List<Student> studentsList =  new List<Student>();

Trying to get the Data to Save into a JSON file so when the program is reopened students can be search.尝试将要保存的数据保存到 JSON 文件中,以便在重新打开程序时可以搜索学生。

Issue: JSON file updates after creating a student object but when exiting and reopening the program it says students do not exist.问题:创建学生对象后 JSON 文件更新,但在退出并重新打开程序时显示学生不存在。

You need to await it你需要await

public static async Task Save() 
{
    using (var file = File.CreateText(_studentRepositoryPath))
    {
        await file.WriteAsync(JsonSerializer.Serialize(studentsList));
    }
}

or just use Write或者只使用Write

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM