sudhakarssd
sudhakarssd

Reputation: 451

How to append node to existing json file using json.net

i am working with json in asp.net using json.NET where on button click values from textbox gets added to json file called country.json. There are two textbox which takes country and its capital as values, country.json file looks like this,

[

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

]

i was able to create json with one node but how to append or add second node to existing json. Here is the c# code ,

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

Upvotes: 0

Views: 3302

Answers (2)

sneusse
sneusse

Reputation: 1691

I needed the same feature and the round-trip was just too expensive. This is what I came up with:

    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(']');
            }
        }


    }

Upvotes: 2

nunespascal
nunespascal

Reputation: 17724

If you want a list, you should be saving a list, not a single node.

Here are the steps:

  1. If file exists, load all nodes from existing file into list.
  2. Add new node when user provides data.
  3. Save list to file.

Upvotes: 3

Related Questions