尝试在C#/JSON中加载和保存对象
困难部分尝试在C#/JSON中加载和保存对象,c#,.net,json,save,load,C#,.net,Json,Save,Load,困难部分 const string _studentRepositoryPath = @"students.json"; static void Save() { using (var file = File.CreateText(_studentRepositoryPath)) { file.WriteAsync(JsonSerializer.Serialize(studentsList));
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>();
const string\u studentRepositoryPath=@“students.json”;
静态void Save(){
使用(var file=file.CreateText(_studentRepositoryPath))
{
WriteAsync(JsonSerializer.Serialize(studentsList));
}
}
静态列表读取(){
返回JsonSerializer.Deserialize(File.ReadAllText(_studentRepositoryPath));
}
静态列表studentsList=新列表();
试图将数据保存到JSON文件中,以便在程序重新打开时,学生可以进行搜索
问题:JSON文件在创建student对象后更新,但在退出并重新打开程序时,会显示student不存在。您需要等待它
public static async Task Save()
{
using (var file = File.CreateText(_studentRepositoryPath))
{
await file.WriteAsync(JsonSerializer.Serialize(studentsList));
}
}
或者只使用你需要等待它
public static async Task Save()
{
using (var file = File.CreateText(_studentRepositoryPath))
{
await file.WriteAsync(JsonSerializer.Serialize(studentsList));
}
}
或者只是使用