为什么在使用 JSON 时不能在.txt上写下绑定列表?



我正在尝试将BindingList的内容添加到一个txt文件中。然而,我总是得到以下错误:

System.NullReferenceException: Object reference not set to an instance of an object. 

我做错了什么?如果有帮助的话,文本文件是空的。

代码:

BindingList<Student> StudentCollection = new BindingList<Student>();
private void btnAddStudent_Click(object sender, EventArgs e)
{
Student StudentSave = new Student
{
ID = txtStudentID.Text,
FirstName = txtFirstName.Text,
LastName = txtLastName.Text,
Age = nudAge.Value,
Height = nudHeight.Value,
Schoolclass = txtSchoolClass.Text,
Gender = cbxGender.Text,
};
cbxStudentIDs.DataSource = StudentCollection;
cbxStudentIDs.DisplayMember = "ID";
StudentCollection.Add(StudentSave);
}
public class Student
{
public string ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Age { get; set; }
public decimal Height { get; set; }
public string Schoolclass { get; set; }
public string Gender { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
string studentCollectionString = File.ReadAllText(FilePath);
StudentCollection = JsonConvert.DeserializeObject<BindingList<Student>>(studentCollectionString);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
string studentCollectionString = JsonConvert.SerializeObject(StudentCollection);
File.WriteAllText(FilePath, studentCollectionString);
}

问题

这就是您将得到异常的地方,正如您所提到的,文本文件是空的,StudentCollection将被设置为null

StudentCollection = JsonConvert.DeserializeObject<BindingList<Student>>(studentCollectionString);

解决方案

您应该这样更改代码:?将确保只有在文本文件中有有效结果的情况下操作才能继续。

JsonConvert.DeserializeObject<BindingList<Student>>(studentCollectionString)?.ToList().ForEach(a => StudentCollection.Add(a));

确保你的文件路径确实存在如果不存在你应该创建文件然后写入文件,也确保你的json不是空的

https://learn.microsoft.com/en-us/dotnet/api/system.io.file.create?view=netcore-3.1

最新更新