简体   繁体   中英

C# serialize and deserialize json to txt file

I'm using NewtonSoft for handling json in my wpf application. I've got a customer that can be saved to a txt file (no database involved). I'm doing that like this:

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;
}

The result looks like this:

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

Then I'm trying to get all customers like this:

if(File.Exists(Settings.databasePath + "customer.json"))
{
    List<Customer> customers;

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

But I receive this error (can't copy the error):

在此处输入图片说明 Already tried to store it like a jArray but that's not working. How do I get this to work?

Any help is going to be appreciated. :)

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 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;
}

Then, just save the JArray of customer :

//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);
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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