追加新数据添加到现有的JSON文件 [英] Appending new data to an existing JSON file

查看:1940
本文介绍了追加新数据添加到现有的JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已搜查高,低,无远弗届的解决办法,并在过去的几个星期试图实现自己的解决方案,但我不能拿出任何东西。

我将不胜AP preciate任何帮助!

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

  {
  费用: {
    名:OneTel移动账单,
    量:39.90,
    由于:28/12/2011,
    复发:1个月,
    带薪:0,
    LastPaid:01/01/2002
  }
}
 

和我的应用程序,当我创建一个新的'费用',我要追加新的费用,以这个现有的JSON文件,所以它看起来像这样:

  {
  费用: {
    名:OneTel移动账单,
    量:39.90,
    由于:28/12/2011,
    复发:1个月,
    带薪:0,
    LastPaid:01/01/2002
  },
  费用: {
    名:还贷,
    量:50.00,
    由于:08/03/2012,
    复发:3个月,
    带薪:0,
    LastPaid:2011年8月12日
  }
}
 

这是我如何创建JSON和写入文件:

 异步公共无效将writeToFile(字符串类型,字符串数据)
{
    文件=等待folder.GetFileAsync(file.FileName);
    IRandomAccessStream writestream =等待file.OpenAsync(FileAccessMode.ReadWrite);


    IOutputStream的OutputStream = writestream.GetOutputStreamAt(0);
    DataWriter datawriter =新DataWriter(的OutputStream);
    datawriter.WriteString(数据);

    等待datawriter.StoreAsync();
    outputstream.FlushAsync()启动()。
}

私人无效CreateExpenseButton_Click(对象发件人,RoutedEventArgs E)
{
    //创建JSON文件,并将其保存将writeToFile();
    JObject jobject =
        新JObject(
            新JProperty(费用,
                新JObject(
                    新JProperty(名称,NameTextBox.Text)
                    新JProperty(额,AmountTextBox.Text)
                    新JProperty(由于,DueTextBox.Text)
                    新JProperty(复发,EveryTextBox.Text ++ EveryComboBox.SelectionBoxItem)
                    新JProperty(付费,0),
                    新JProperty(LastPaid,从不)
                           )
                         )
                   );
    尝试
    {
        将writeToFile(费用,jobject.ToString());

        //现在关闭弹出。
        this.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
    }
    赶上(例外的例外)
    {
        Debug.Write(exception.Message);

    }
}
 

我使用的詹姆斯牛顿王Json.NET库,这是pretty的真棒,但即使在阅读附带的文件,我完全不知道如何读的JSON文件,将数据添加到它。

是否有周围的任何示例,演示如何做到这一点,或者您也可以推荐其他库的C#,让我做到这一点?

修改

这是我如何看从JSON文件中的单个费用:

  JObject JSON = JObject.Parse(数据);
        费用费用=新的费用
        {
            金额=(字符串)JSON [费用] [数量],
            由于=(字符串)JSON [费用] [由于],
            名称=(字符串)JSON [费用] [名称]
        };

        Debug.Write(expense.Amount);
 

解决方案

既然你可以直接读入费用的对象,你应该能够到这样的对象添加到一个名单,其中,费用> - 添加新的数据作为费用对象添加到列表(直接从您的表单数据,或以其它方式)。

在这一点上,你应该能够编写出名单,其中,费用和GT; 出使用JSON.NET - 它应该创建列表的护理

我建议你一直留有一个名单,其中,费用和GT; ,即使它仅包含一个项目,因为它会使序列化和反序列化更容易

I have searched high and low, and far and wide for a solution to this, and have spent the last few weeks trying to implement my own solution, but I just can't come up with anything.

I would greatly appreciate any help at all!

I have a file, which looks like, (file.json):

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

And in my app, when I create a new 'Expense', I want to append that new Expense to this existing JSON file, so it looks like so:

{
  "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"
  }
}

And this is how I am creating the JSON and writing to the file:

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

    }
}

I am using the Json.NET library from James Newton King, and it's pretty awesome but even after reading the included documentation, I have absolutely no idea how to read the JSON file and append data to it.

Are there any samples around that demonstrate how this is done, or can you recommend another library for C# that would allow me to accomplish this?

Edit

This is how I am reading a single expense from the json file:

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

解决方案

Since you can read directly into an Expense object, you should be able to add such an object to a List<Expense> - add the new data as an Expense object to the list (directly from your form data, or otherwise).

At this point you should be able to write out the List<Expense> out using JSON.NET - it should take care of creating the list.

I suggest you always save a List<Expense>, even if it contains only one item as it would make serializing and deserializing easier.

这篇关于追加新数据添加到现有的JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆