locked
How to insert json file in c# RRS feed

  • Question

  • User1839056048 posted

    Hi,

    I want to insert a record in json file

    following is my json file

    [
      {
        "id": 123,
        "name": "Mukesh Kumar",
        "street": "El Camino Real",
        "city": "New Delhi",
        "zipcode": 95014
      },
      {
        "id": 456,
        "name": "Mkesh Kumar",
        "street": "l Camino Real",
        "city": "Nw Delhi",
        "zipcode": 944
      }
    
    ]

    How to do this

    Regards

    Baiju

    Monday, October 29, 2018 11:56 AM

Answers

  • User-821857111 posted

    Read the contents of the file and deserialize it to a collection in C#, add the new record then serialise to JSON and overwrite the existing file.

    Here's the class:

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public int Zipcode { get; set; }
    }

    Here's some code to do what you need:

    var path = @"path_to_json_file";
    var json = File.ReadAllText(path);
    var people = JsonConvert.DeserializeObject<List<Person>>(json);
    people.Add(new Person{Id = 789, Name = "Mike", City = "ASP.NET", Street = "MVC Avenue", Zipcode = 12345});
    json = JsonConvert.SerializeObject(people);
    File.WriteAllText(path, json);
    
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 29, 2018 12:10 PM