C# serialize and deserialize json to txt file
I would do it like follows:
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<List<Customer>>(json); customers.Add(newCustomer); File.WriteAllText(pathToTheFile, JsonConvert.SerializeObject(customers));}public Customer GetCustomer(string id){ var json = File.ReadAllText(pathToTheFile); var customers = JsonConvert.DeserializeObject<List<Customer>>(json); var result = new Customer(); foreach (var c in customers) { if (c.Id == id) { result = c; break; } } return result;}
Your problem is that you try to get a List of Customer from your file while you are saving only one customer.
If you want store multiple customers in your file you have to create a JArray and add your customer into it :
//The customers arrayprivate JArray customers = new JArray();//Store new customer in arraypublic 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;}
Then, just save the JArray of customer :
//Save arraypublic void Save(){ StreamWriter file = File.CreateText(Settings.databasePath + "customer.json"); using (JsonTextWriter writer = new JsonTextWriter(file)) { //Save JArray of customers customers.WriteTo(writer); }}
You'll probably have to adapt this code to your own needs.
I try my best to write correct english, but be free to correct me.