【问题标题】:How to append node to existing json file using json.net如何使用 json.net 将节点附加到现有的 json 文件
【发布时间】:2026-02-06 08:40:01
【问题描述】:

我正在使用 json.NET 在 asp.net 中处理 json,其中文本框中的按钮单击值被添加到名为 country.json 的 json 文件中。有两个以国家及其首都为值的文本框, country.json 文件长这样,

[

    {
        "country":"USA",
        "capital":"New York"
    },
    {
        "country":"China",
        "capital":"Bejing"
    },
    {
        "country":"India",
        "capital":"New Delhi"
    }

]

我能够使用一个节点创建 json,但是如何将第二个节点附加或添加到现有 json。 这是c#代码,

 public class country
    {
        public string Country { get; set; }
        public string Capital { get; set; }
    }
 protected void btnSubmit_Click(object sender, EventArgs e)
    {

                country ctry = new country();
                ctry.Country = txtCtry.Text;
                ctry.Capital = txtCapital.Text;

      File.AppendAllText(MapPath("Data/countrycaps.json"),JsonConvert.SerializeObject(ctry,Formatting.Indented));
    }

【问题讨论】:

    标签: c# asp.net json json.net


    【解决方案1】:

    如果你想要一个列表,你应该保存一个列表,而不是单个节点。

    步骤如下:

    1. 如果文件存在,则将现有文件中的所有节点加载到列表中。
    2. 用户提供数据时添加新节点。
    3. 将列表保存到文件。

    【讨论】:

      【解决方案2】:

      我需要相同的功能,而且往返太贵了。 这是我想出的:

          private static void AppendTransaction(Transaction transaction)
          {
              const string filename = "transactions.json";
              bool firstTransaction = !File.Exists(filename);
      
              JsonSerializer ser = new JsonSerializer();
              ser.Formatting = Formatting.Indented;
              ser.TypeNameHandling = TypeNameHandling.Auto;
      
              using (var fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
              {
                  Encoding enc = firstTransaction ? new UTF8Encoding(true) : new UTF8Encoding(false);
      
                  using (var sw = new StreamWriter(fs, enc))
                  using (var jtw = new JsonTextWriter(sw))
                  {
                      if (firstTransaction)
                      {
                          sw.Write("[");
                          sw.Flush();
                      }
      
                      else
                      {
                          fs.Seek(-Encoding.UTF8.GetByteCount("]"), SeekOrigin.End);
                          sw.Write(",");
                          sw.Flush();
                      }
      
                      ser.Serialize(jtw, transaction);
                      sw.Write(']');
                  }
              }
      
      
          }
      

      【讨论】:

        最近更新 更多