Capstone C: JSON persistence

A to-do list that forgets on exit is a demo. The file is where the application meets the future: it has to be written, read by a later version, and rejected when the later version wrote something this one does not understand. The repository of this lesson is the smallest honest version of that.

The envelope

The file is not a bare array of tasks. It is an object with a version and the tasks, so a later format can recognise an older file and refuse a newer one instead of misreading it:

Two settings matter. WriteIndented makes the file readable by a human and by a diff. PropertyNamingPolicy = JsonNamingPolicy.CamelCase writes version and tasks in the style of the rest of the web, and the same options object must be passed to Deserialize as well: a default deserialiser is case-sensitive and would read version as 0, which turns a version check into a false alarm.

The task is stored as three strings: the id, the title and the state name. The state is the enum's ToString, so the file says "Done" and not 2; a number changes meaning the day an enum value is inserted, and the name does not.

The repository

Save maps the list to a list of DTOs and writes the envelope. Load reads the envelope, checks the version, creates an empty list and restores every task through TaskList.Restore. The restore takes the id and the state that were saved, and it moves the next-id counter past the highest id it saw, so a task added after a load does not collide with a saved one.

The repository is not the place for the presenter's rules. It does not reject a duplicate title or a long one: the model did that when the file was written, and a file edited by hand is a support case, not a validation path the screen should carry. What it does enforce is the version, because a format it does not know is the one thing it cannot guess.

A version that is checked

CurrentVersion is a constant of the repository, and Load throws InvalidDataException for any other value. There are two other designs and both are worse here. Ignoring the version makes a newer file load into an older application with missing fields. Migrating every old version inside Load is right for a format with a long life; a capstone with one version does not have the history to test it.

A version check that only exists in Load is enough, because the application writes the version itself and never reads a file to edit it in place. A save always replaces the file with the current format.

The storage in a program that runs

The model, the repository and a real temporary file: save, load, compare the counts, write a version 2 file by hand and read it, then delete the file. It was built and run in the container:

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; Console.WriteLine("a to-do list saved as JSON"); var path = Path.Combine(Path.GetTempPath(), "aredel-todo-test.json"); var list = new TaskList(); var first = list.Add("Write"); first.Start(); first.Complete(); list.Add("Review").Start(); var repository = new TodoRepository(path); repository.Save(list); Console.WriteLine($"saved: {File.Exists(path)}"); Console.WriteLine($"camelCase: {File.ReadAllText(path).Contains("\"version\": 1")}"); var back = repository.Load(); Console.WriteLine($"loaded: {back.Count} tasks"); Console.WriteLine($"ids: {string.Join(", ", back.Items.Select(item => item.Id))}"); Console.WriteLine($"states: {string.Join(", ", back.Items.Select(item => item.State))}"); Console.WriteLine($"round trip: {back.DoneCount == list.DoneCount && back.ActiveCount == list.ActiveCount}"); File.WriteAllText(path, "{\"version\":2,\"tasks\":[]}"); try { repository.Load(); } catch (InvalidDataException error) { Console.WriteLine($"bad version: {error.Message}"); } File.Delete(path); Console.WriteLine($"removed: {!File.Exists(path)}"); internal enum TaskState { New, Active, Done, } internal sealed class TodoItem { internal TodoItem(string id, string title, TaskState state) { Id = id; Title = title; State = state; } public string Id { get; } public string Title { get; } public TaskState State { get; private set; } public void Start() => State = TaskState.Active; public void Complete() => State = TaskState.Done; } internal sealed class TaskList { private readonly List<TodoItem> _items = new(); private int _next = 1; public IReadOnlyList<TodoItem> Items => _items; public int Count => _items.Count; public int ActiveCount => _items.Count(item => item.State == TaskState.Active); public int DoneCount => _items.Count(item => item.State == TaskState.Done); public TodoItem Add(string title) { var added = new TodoItem($"T-{_next++}", title, TaskState.New); _items.Add(added); return added; } public void Restore(string id, string title, TaskState state) { _items.Add(new TodoItem(id, title, state)); if (int.TryParse(id.AsSpan(2), out var number)) { _next = Math.Max(_next, number + 1); } } } internal sealed record TaskDto(string Id, string Title, string State); internal sealed record Envelope(int Version, List<TaskDto> Tasks); internal sealed class TodoRepository { public const int CurrentVersion = 1; private static readonly JsonSerializerOptions Options = new() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; private readonly string _path; public TodoRepository(string path) => _path = path; public void Save(TaskList list) { var tasks = new List<TaskDto>(); foreach (var item in list.Items) { tasks.Add(new TaskDto(item.Id, item.Title, item.State.ToString())); } File.WriteAllText(_path, JsonSerializer.Serialize(new Envelope(CurrentVersion, tasks), Options)); } public TaskList Load() { var envelope = JsonSerializer.Deserialize<Envelope>(File.ReadAllText(_path), Options)!; if (envelope.Version != CurrentVersion) { throw new InvalidDataException($"Unsupported version {envelope.Version}."); } var list = new TaskList(); foreach (var task in envelope.Tasks) { list.Restore(task.Id, task.Title, Enum.Parse<TaskState>(task.State)); } return list; } }

dotnet run

a to-do list saved as JSON
saved: True
camelCase: True
loaded: 2 tasks
ids: T-1, T-2
states: Done, Active
round trip: True
bad version: Unsupported version 2.
removed: True

The output is the real run. The file existed after the save and its text used the camelCase names. The load returned two tasks with the same ids and states, and the round trip compared the counts rather than the objects, because the ids and the states are what a later run cares about. The hand-written version 2 file was rejected with the message that names the version, and the delete left nothing behind.

Rules for a saved file

Exercises

  1. Add a savedAt field with a date to the envelope and print it after the load.
  2. Change the state to an integer and explain what a later insert of an enum value would break.
  3. Make Load reject a file with a duplicate id and add that case to the run.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the file hold at the top level?

    Answer

    An object with a version and the tasks

    The envelope leaves room for a second field.

  2. Which option writes camelCase names?

    Answer

    PropertyNamingPolicy = JsonNamingPolicy.CamelCase

    The run checks for "version": 1 in the text.

  3. What happens if the options are not passed to Deserialize?

    Answer

    The camelCase names are not matched and the version reads as 0

    The default deserialiser is case-sensitive.

  4. Why is the state saved as a name?

    Answer

    A number changes meaning when an enum value is inserted

    The name is the stable part of the value.

  5. What does Restore do with the id counter?

    Answer

    It moves it past the highest saved id

    A task added after a load must not collide.

  6. What did the loaded list contain?

    Answer

    Two tasks with the same ids and states

    The round trip printed True for the counts.

  7. What exception does a version 2 file raise?

    Answer

    InvalidDataException

    The repository throws it with the version in the message.

  8. Where should an installed application write its settings?

    Answer

    In the user application-data folder

    Program Files is not writable for a standard user.

  9. When does the form of the next lesson save?

    Answer

    After a command and on close

    The presenter raises Changed after each command.

  10. Why test with a real file?

    Answer

    Encoding, the BOM and file locking are not in a string

    The run uses a temporary file and deletes it.

Every listing on this page is plain .NET code with no window in it: it was built and run with the .NET SDK 10.0.303 on Alpine Linux 3.24.3 (x86_64) in a Docker container, and the output printed below the program is that run. The WinForms pages of this course are built for net10.0-windows against Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed and never run on Linux: WinForms needs Windows.

Article author: Arthur Isaev