Search code examples
c#arraysjsonlistjson-deserialization

Adding a dictionary to an array in an existing json file


I have a local json file that I wish to be able to add a new dictionary to the existing array within the file using data entries from a form.
i.e. turn this:

[
    {
    "name": "Product1",
    "type": "Drink",
    "costS": 2.5,
    "costB": 2.4,
    "amount": "none",
    "info": "keep cold"
    }
]

into:

[
    {
    "name": "Product1",
    "type": "Drink",
    "costS": "2.5",
    "costB": "2.4",
    "amount": "none",
    "info": "keep cold"
    }
    {"name": "Product2",
    "type": "Food",
    "costS": "2.8",
    "costB": "4",
    "amount": "34",
    "info": "keep hot"
    }
]

where each value comes from a form element ("name" value from txtName, "type" value from txtType, etc). I have so far tried adapting answers from this post and this post to no avail.

I am very new to c# so it would be much appreciated if answers could be explained to at least a small degree of depth please. Any replies are appreciated however.


Solution

  • You can do like this by using NewtonSoft.Json. first, deserialize the JSON to List<Example> then add the item to this list. and then finally you can serialize the List<Example> to string.

    var list = JsonConvert.DeserializeObject<List<Example>>(json);
    Example example = new Example();
    example.name = "Product2";
    example.info = "keep hot";
    example.amount = "34";
    example.costB = "4";
    example.costS = "2.8";
    example.type = "Food";
    list.Add(example);
    
    string output = JsonConvert.SerializeObject(list);
    
    public class Example
    {
        public string name { get; set; }
        public string type { get; set; }
        public string costS { get; set; }
        public string costB { get; set; }
        public string amount { get; set; }
        public string info { get; set; }
    }