C#序列化并反序列化json到txt文件

我正在使用NewtonSoft在我的wpf应用程序中处理json。 我有一个客户可以保存到txt文件(不涉及数据库)。 我是这样做的:

public int store(string[] reservation) { JObject customer = new JObject( new JProperty("id", this.getNewId()), new JProperty("name", reservation[0]), new JProperty("address", reservation[1]), new JProperty("gender", reservation[2]), new JProperty("age", reservation[3]) ); using (StreamWriter file = File.CreateText(Settings.databasePath + "customer.json")) using (JsonTextWriter writer = new JsonTextWriter(file)) { customer.WriteTo(writer); } return 1; } 

结果如下:

 {"id":1,"name":"Lars","address":"Bosch 10","gender":"Man","age":"19"} 

然后我试图让所有客户都这样:

 if(File.Exists(Settings.databasePath + "customer.json")) { List customers; using (StreamReader r = new StreamReader(Settings.databasePath + "customer.json")) { string json = r.ReadToEnd(); customers = JsonConvert.DeserializeObject<List>(json); } } 

但我收到此错误(无法复制错误):

在此处输入图像描述 已经尝试将其存储为jArray,但这不起作用。 我如何让它工作?

任何帮助将不胜感激。 🙂

我会这样做:

 public class Customer { public string Id { get; set; } public string Name { get; set; } public string Address { get; set; } public string Gender { get; set; } public int Age { get; set; } } public void AddCustomer(Customer newCustomer) { var json = File.ReadAllText(pathToTheFile); var customers = JsonConvert.DeserializeObject>(json); customers.Add(newCustomer); File.WriteAllText(pathToTheFile", JsonConvert.SerializeObject(customers)); } public Customer GetCustomer(string id) { var json = File.ReadAllText(pathToTheFile); var customers = JsonConvert.DeserializeObject>(json); var result = new Customer(); foreach (var c in customers) { if (c.Id == id) { result = c; break; } } return result; } 

您的问题是,当您只保存一个客户时,您尝试从文件中获取客户列表

如果要在文件中存储多个客户,则必须创建JArray并将客户添加到其中:

 //The customers array private JArray customers = new JArray(); //Store new customer in array public int Store(string[] reservation) { JObject customer = new JObject( new JProperty("id", this.getNewId()), new JProperty("name", reservation[0]), new JProperty("address", reservation[1]), new JProperty("gender", reservation[2]), new JProperty("age", reservation[3]) ); //Add customer to customers array customers.add(customer); return 1; } 

然后,只需保存客户的JArray:

 //Save array public void Save() { StreamWriter file = File.CreateText(Settings.databasePath + "customer.json"); using (JsonTextWriter writer = new JsonTextWriter(file)) { //Save JArray of customers customers.WriteTo(writer); } } 

您可能必须根据自己的需要调整此代码。

我尽力写出正确的英语,但可以自由地纠正我。