我已经搜索了高低,远远地寻找解决方案,并且花了最近几周试图实现我自己的解决方案,但我无法想出任何东西。
我非常感谢任何帮助!
我有一个文件,看起来像,(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文件中读取单个费用的方式:
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);
答案 0 :(得分:0)
您可以尝试将数据反序列化为对象Expense并添加数据,然后将对象(对象列表)序列化为file。
答案 1 :(得分:0)
由于您可以直接读取Expense
对象,因此您应该能够将此类对象添加到List<Expense>
- 将新数据作为Expense
对象添加到列表中(直接来自您的表单数据,或其他)。
此时你应该能够使用JSON.NET写出List<Expense>
- 它应该负责创建列表。
我建议您始终保存List<Expense>
,即使它只包含一个项目,因为它会使序列化和反序列化更容易。