append to a json file in csharp

To append data to an existing JSON file in C#, you can use the Newtonsoft.Json package. First, you would need to read the existing JSON file and deserialize it into a list of objects. Next, you can add the new data to the list and serialize it back into JSON format. Finally, you can write the JSON string to the same file to append the new data.

Here's some sample code:

main.cs
using System.IO;
using Newtonsoft.Json;

// Define a class to hold your data
public class MyData {
    public int Id { get; set; }
    public string Name { get; set; }
}

// Read the existing JSON file into a list of objects
List<MyData> dataList;
using (StreamReader file = File.OpenText("data.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    dataList = (List<MyData>)serializer.Deserialize(file, typeof(List<MyData>));
}

// Add new data to the list
MyData newData = new MyData { Id = 1, Name = "New Object" };
dataList.Add(newData);

// Serialize the updated list back into JSON format
string json = JsonConvert.SerializeObject(dataList, Formatting.Indented);

// Write the JSON string to the same file to append the new data
using (StreamWriter file = File.CreateText("data.json"))
{
    file.Write(json);
}
831 chars
30 lines

This code assumes that your JSON file contains an array of objects, like this:

[
    { "Id": 1, "Name": "Object 1" },
    { "Id": 2, "Name": "Object 2" }
]
77 chars
5 lines

If your file contains a single object, you would need to modify the deserialization step accordingly. Note also that this code simply appends to the file; if you want to overwrite the file completely, you would use File.WriteAllText instead of File.CreateText.

gistlibby LogSnag