14

I'm trying to automate the addition of new objects to an existing JSON file. I looked all around the web but only found adding data and stuff but not a whole object. This is how the file that I want to edit looks:

[
    {"id":"123","name":"carl"}
]

and I want to go to

[
     {"id":"123","name":"carl"},
     {"id":"1234","name":"carl2"}
]

Thank you for all your answers but I don't think everyone completely understands what i mean I have tried some of the answers but then I get this:

[
    "{\"id\":\"123\",\"name\":\"carl\"}"
]"{\"id\":\"1234\",\"name\":\"carl2\"}"

and I want everything in between the [].

sajadre
  • 1,141
  • 2
  • 15
  • 30
Joris van Roy
  • 183
  • 1
  • 1
  • 12
  • 4
    Deserialize to a c# data type (or `JObject`, or `dynamic`, etc.), add a new item to the list, then serialize back to a string? – crashmstr Oct 12 '15 at 12:28

6 Answers6

18

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);
Michael Mairegger
  • 6,833
  • 28
  • 41
8

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

HadiRj
  • 1,015
  • 3
  • 21
  • 41
Alex
  • 37,502
  • 51
  • 204
  • 332
3

A better performing solution than serializing/deserializing what may be a large file would be to open a FileStream, seek 1 character before the end, then serialize and write your new object into the array, then write a closing bracket. See this question C# How to delete last 2 characters from text file and write into the same line at the end my text?, I'll copy the code here - you already know how to serialize your object and encode it into bytes.

using(var fs = new FileStream("file.json")) {    
    fs.Seek(-1,SeekOrigin.End);        
    fs.Write(mySerializedJSONObjAsBytes,0,mySerializedJSONObjAsBytes.Length); // include a leading comma character if required
    fs.Write(squareBracketByte, 0, 1);
    fs.SetLength(fs.Position); //Only needed if new content may be smaller than old
}

Sorry haven't tested any of that, it's off the top of my head. Pro-tip: wrap FileStream in a StreamWriter so can write strings directly.

LMK
  • 1,496
  • 1
  • 13
  • 15
  • This is the best answer since all the others deserialize/serialize the whole json file only to add one element to the list, which is unnecessary and will impact performance if the file is big and/or you need to add new elements frequently. – Canovas Jun 22 '22 at 21:50
2

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);
Arthur Rey
  • 2,990
  • 3
  • 19
  • 42
  • 2
    Since you are trying to add a List of objects to a List, you should use AddRange() instead of Add() – Abhishek Dec 05 '16 at 07:49
1

this would be a sample for you:

var list = JsonConvert.DeserializeObject<List<Example>>(json);
    Example example = new Example();
    example.name = "Product2";
    example.id="1";
    list.Add(example);
    
    string output = JsonConvert.SerializeObject(list);
    
    public class Example
    {
        public string id {get;set;}
        public string name { get; set; }
        
    }
sajadre
  • 1,141
  • 2
  • 15
  • 30
0

I have been looking for a solution to this exact question for a week now. I finally figured out how to append it to the existing json array and not add it as a solo object after the array. Make sure you are using WriteAllText and not AppendAllText. Here is what I did:

JArray array = JsonConvert.DeserializeObject<JArray (jsonFile);

JObject obj = new JObject();
obj.Add("ID", "123");
obj.Add("Name", "Brian");

array.Add(obj);

var jsonToOutput = JsonConvert.SerializeObject(array, Formatting.Indented);
File.WriteAllText("fileName.json", jsonToOutput);