C#将json序列化和反序列化为txt文件 [英] C# serialize and deserialize json to txt file

查看:1112
本文介绍了C#将json序列化和反序列化为txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

结果如下:

{"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):

已经尝试将其像jArray一样存储,但无法正常工作.我如何使它工作?

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

这篇关于C#将json序列化和反序列化为txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆