0

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.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Greefin
  • 3
  • 1
  • This probably isn’t a very good question on this site since it comes off as “could someone write this code for me.” Which part are you having trouble with? Deserializing the JSON into an array/list? Adding an object to that? Serializing the data back? – Sami Kuhmonen Mar 06 '21 at 05:48

1 Answers1

1

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; }
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197