wpf C# 将json序列化和反序列化为txt文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41427643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:58:56  来源:igfitidea点击:

C# serialize and deserialize json to txt file

c#jsonwpflistjson.net

提问by Jenssen

I'm using NewtonSoftfor 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:

我正在使用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;
}

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

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

enter image description hereAlready tried to store it like a jArray but that's not working. How do I get this to work?

在此处输入图片说明已经尝试像 jArray 一样存储它,但这不起作用。我如何让这个工作?

Any help is going to be appreciated. :)

任何帮助将不胜感激。:)

采纳答案by Mahdi

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

回答by csblo

Your problem is that you try to get a List of Customerfrom your file while you are saving only onecustomer.

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

If you want store multiple customers in your file you have to create a JArrayand add your customer into it :

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

Then, just save the JArray of customer :

然后,只需保存 customer 的 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);
    }
}

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.

我尽力写出正确的英语,但请随时纠正我。