json add new object to existing json file C#

If you use json.NET you can simply deserialize and serialize the json.

var list = JsonConvert.DeserializeObject<List<Person>>(myJsonString);
list.Add(new Person(1234,"carl2");
var convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented);

Using Json.Net

//load from file
var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";

var array = JArray.Parse(initialJson);

var itemToAdd = new JObject();
itemToAdd["id"] = 1234;
itemToAdd["name"] = "carl2";
array.Add(itemToAdd);

var jsonToOutput = JsonConvert.SerializeObject(array, Formatting.Indented);

//save to file here

Using this method doesn't require strongly typed objects

You could replace this bit:

//load from file
var initialJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";

With

var initialJson = File.ReadAllText(@"c:\myjson.json")

To load the json from a text file


You could create a method:

public string AddObjectsToJson<T>(string json, List<T> objects)
{
    List<T> list = JsonConvert.DeserializeObject<List<T>>(json);
    list.AddRange(objects);
    return JsonConvert.SerializeObject(list);
}

Then use it like this:

string baseJson = "[{\"id\":\"123\",\"name\":\"carl\"}]";
List<Person> personsToAdd = new List<Person>() { new Person(1234,"carl2") };

string updatedJson = AddObjectsToJson(baseJson, personsToAdd);

Tags:

C#

Json