16

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 [].

1
  • 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? Commented Oct 12, 2015 at 12:28

6 Answers 6

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Does this actually maintain the order?
Well, since order is not guaranteed in JSON, it really shouldn't matter.
@PRMan JSON preserves the order of array items, but not that of dictionary items.
Is this a good option to do if you have a large Json file?
7

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

Comments

4

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.

1 Comment

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.
1

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

1 Comment

Since you are trying to add a List of objects to a List, you should use AddRange() instead of Add()
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; }
        
    }

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.