gpt4 book ai didi

c# - 将新数据附加到现有的 JSON 文件

转载 作者:太空宇宙 更新时间:2023-11-03 16:37:41 25 4
gpt4 key购买 nike

我到处寻找解决方案,并在过去几周尝试实现我自己的解决方案,但我就是想不出任何办法。

如果有任何帮助,我将不胜感激!

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

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

在我的应用程序中,当我创建一个新的“费用”时,我想将该新费用附加到这个现有的 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 文件中读取单笔费用的方式:

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

最佳答案

您可以尝试将数据反序列化为对象 Expence 并添加您的数据,然后将对象(对象列表)序列化为文件。

关于c# - 将新数据附加到现有的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8551075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com