向现有的JSON文件追加新数据

3

我已经四处寻找解决方案,花费了几个星期尝试实现自己的解决方案,但是我无法想到任何东西。

我非常感谢任何帮助!

我有一个文件,它看起来像这样(file.json):

{
  "Expense": {
    "Name": "OneTel Mobile Bill",
    "Amount": "39.90",
    "Due": "28/12/2011",
    "Recurrence": "1 Months",
    "Paid": "0",
    "LastPaid": "01/01/2002"
  }
}

在我的应用程序中,当我创建一个新的“Expense”时,我希望将该新“Expense”附加到现有的JSON文件中,使它看起来像这样:

{
  "Expense": {
    "Name": "OneTel Mobile Bill",
    "Amount": "39.90",
    "Due": "28/12/2011",
    "Recurrence": "1 Months",
    "Paid": "0",
    "LastPaid": "01/01/2002"
  },
  "Expense": {
    "Name": "Loan Repayment",
    "Amount": "50.00",
    "Due": "08/03/2012",
    "Recurrence": "3 Months",
    "Paid": "0",
    "LastPaid": "08/12/2011"
  }
}

以下是我创建JSON并写入文件的方法:

async public void WriteToFile(string type, string data)
{
    file = await folder.GetFileAsync(file.FileName);
    IRandomAccessStream writestream = await file.OpenAsync(FileAccessMode.ReadWrite);


    IOutputStream outputstream = writestream.GetOutputStreamAt(0);
    DataWriter datawriter = new DataWriter(outputstream);
    datawriter.WriteString(data);

    await datawriter.StoreAsync();
    outputstream.FlushAsync().Start();
}

private void CreateExpenseButton_Click(object sender, RoutedEventArgs e)
{
    //Create the Json file and save it with WriteToFile();
    JObject jobject =
        new JObject(
            new JProperty("Expense",
                new JObject(
                    new JProperty("Name", NameTextBox.Text),
                    new JProperty("Amount", AmountTextBox.Text),
                    new JProperty("Due", DueTextBox.Text),
                    new JProperty("Recurrence", EveryTextBox.Text + " " + EveryComboBox.SelectionBoxItem),
                    new JProperty("Paid", "0"),
                    new JProperty("LastPaid", "Never")
                           )
                         )
                   );
    try
    {
        WriteToFile(Expenses, jobject.ToString());

        // Close the flyout now.
        this.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
    }
    catch (Exception exception)
    {
        Debug.Write(exception.Message);

    }
}

我正在使用James Newton King的Json.NET库,非常棒,但即使阅读了包含的文档,我仍然不知道如何读取JSON文件并向其附加数据。是否有任何演示如何完成此操作的示例或您可以推荐另一个C#库以允许我完成此操作?

编辑

这是我从json文件中读取单个expense的方式:

        JObject json = JObject.Parse(data);
        Expense expense = new Expense
        {
            Amount = (string)json["Expense"]["Amount"],
            Due = (string)json["Expense"]["Due"],
            Name = (string)json["Expense"]["Name"]
        };

        Debug.Write(expense.Amount);

你是否曾经从文件中读取过数据?你是否曾经将数据反序列化为对象? - Oded
我已经更新了我的问题并包含了我如何从文件中读取的内容。但是,这是另一个问题;我知道如何读取1个“支出”,但现在不知道如何从一个文件中读取多个支出的值。谢谢你的询问。 - Jason
2个回答

1
你可以尝试将数据反序列化为一个名为Expence的对象,并添加你的数据,然后将该对象(对象列表)序列化到文件中。

感谢@Fossmo, 等我有足够的声望后,我会回来点赞的。 - Jason
@Jason 你好像从来没有回来过 :P - Chax

0

由于您可以直接读取Expense对象,所以应该能够将这样的对象添加到List<Expense>中-将新数据作为Expense对象直接添加到列表中(从表单数据或其他方式)。

此时,您应该能够使用JSON.NET写出List<Expense> - 它应该会处理创建列表的工作。

我建议您始终保存List<Expense>,即使它只包含一个项目,因为这样做会使序列化和反序列化更容易。


谢谢@Oded。所以,如果我理解正确,我可以从文件中读取,将其转换为List<Expense>,附加新数据,然后再次保存所有内容到文件中;用所有内容覆盖该文件的现有内容? - Jason
@Jason - JSON.NET 应该能够直接转换为 List<Expense>,而你已经理解得非常好了。这种方法唯一的问题是随着文件变得越来越大,性能会越来越差。 - Oded
非常感谢@Oded!目前这只是一个个人项目,对性能不太在意,但随着应用程序的发展,我一定会研究更适合的方法。 - Jason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接