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.

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? Commented Mar 6, 2021 at 5:48

1 Answer 1

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

1 Comment

@Greefin enjoy your day :)

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.