12

I'm trying to automate the adding of new objects to an existing json file. I looked all around the web but only found adding data and stuff but not an whole object. This is how the file that i wanna 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 is completely understanding 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 everthing inbetween the [].

Joris van Roy
  • 163
  • 1
  • 1
  • 11
  • 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

5 Answers5

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,503
  • 28
  • 40
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,005
  • 3
  • 22
  • 40
Alex
  • 35,969
  • 49
  • 197
  • 322
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,791
  • 3
  • 17
  • 38
  • 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
2

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,376
  • 1
  • 12
  • 13
0

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,055
  • 2
  • 14
  • 27