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

时间:2017-01-02 13:19:15

标签: c# json wpf list json.net

我在我的wpf应用程序中使用NewtonSoft来处理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<Customer> customers;

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

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

enter image description here已经尝试将其存储为jArray,但这不起作用。我如何让它工作?

任何帮助都将受到赞赏。 :)

2 个答案:

答案 0 :(得分:5)

我会这样做:

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

答案 1 :(得分:2)

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

如果您想在文件中存储多个客户,则必须创建 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);
    }
}

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

我尽力写出正确的英语,但可以随意纠正我。