Skip to main content
 首页 » 编程设计

c#之读取、写入和附加到 JSON 文件

2024年02月23日16del

一段时间以来,我一直在尝试正确解析一些 json 文件,但似乎无法正确解析。我试过很多教程和 json.net 库,但似乎找不到正确的方法来解决这个问题。我的文件都具有相同的格式:

文件.json:

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

现在,我有两个问题。但首先,我知道如何编写 json 文件。所以这对我来说不是问题。但是我的两个问题是:

如何读取 json 字符串/文件,例如: (伪代码)

FOREACH VAR EXPENSE IN EXPENSES  
OUTPUT EXPENSE.NAME  
OUTPUT EXPENSE.AMOUNT  

等等等等......

我的第二个问题是:

如何将全新的“费用”附加到现有的 json 文件?

非常感谢您对此的帮助。

谢谢

我正在像这样将 json 写入文件:

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

请您参考如下方法:

我认为,如果您创建一个 Expense 类,然后序列化并读取一组 Expense 对象(即 List<Expense>),您会轻松得多。

public class Expense 
{ 
    public string Name { get; set; } 
    public decimal Amount { get; set; } 
    public DateTime Due { get; set; } 
    public string Recurrence { get; set; } 
    public decimal Paid { get; set; } 
    public DateTime LastPaid{ get; set; } 
} 
 
public class ExpenseCollection : System.Collections.Generic.List<Expense> 
{ 
 
} 

然后您可以使用内置的 JavaScriptSerializer类。

创建 JSON 的粗略代码:

        ExpenseCollection cExpenses = new ExpenseCollection(); 
        // ToDo: Fill the expenses collection 
        var sJSON = (new System.Web.Script.Serialization.JavaScriptSerializer).Serialize(cExpenses); 
        // ToDo: Write sJSON to a file 

阅读它(注意这可能需要一些调整):

        string sJSON; 
        // ToDo: Read the json from a file 
        ExpenseCollection cExpenses = (new System.Web.Script.Serialization.JavaScriptSerializer).Deserialize<ExpenseCollection>(sJSON); 
        // ToDo: Write sJSON to a file