Here is a simple example which I use Bogus library to mock-up data. The code was done in a console project but will work with any project type.
Model
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public Person(int identifier)
{
Id = identifier;
}
public Person() { }
public string Details => $"{Id,-4}{FirstName} {LastName} {BirthDate:d}";
}
Create some data
public class BogusOperations
{
public static List<Person> People(int count = 10)
{
int identifier = 1;
Faker<Person> fakePerson = new Faker<Person>()
.CustomInstantiator(f => new Person(identifier++))
.RuleFor(p => p.FirstName, f => f.Person.FirstName)
.RuleFor(p => p.LastName, f => f.Person.LastName)
.RuleFor(p => p.BirthDate, f => f.Date.Past(10))
;
return fakePerson.Generate(count);
}
}
Read/write operations
public class Operations
{
private static string FileName => "People.json";
public static JsonSerializerOptions Indented
=> new() { WriteIndented = true };
public static List<Person> Read()
{
var list = JsonSerializer.Deserialize<List<Person>>(File.ReadAllText(FileName));
return list;
}
public static void Save(List<Person> list)
{
File.WriteAllText(FileName, JsonSerializer.Serialize(list, Indented));
}
}
Run it
Operations.Save(BogusOperations.People(2));
var people = Operations.Read();
foreach (var person in people)
{
Console.WriteLine(person.Details);
}
people.Add(new Person()
{
Id = 3,
FirstName = "Jim",
LastName = "Smith",
BirthDate = new DateTime(1990,1,1)
});
Operations.Save(people);
Console.WriteLine();
people = Operations.Read();
foreach (var person in people)
{
Console.WriteLine(person.Details);
}