我已经到处寻找解决方案,并且在过去的几周里一直在尝试实施我自己的解决方案,但我什么也想不出来。
我将非常感谢任何帮助!
我有一个文件,看起来像,(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);