Menu
CoddyTech

Saving JSON

Part of the C# and .NET Basics section of Coddy's ASP.NET Core journey. Lesson 7 of 20.

A List<T> is an array that grows: Add puts an item at the end and Count says how many it holds. To keep a list after the program ends, write it to a file. JSON is a text format that programs and web APIs use to save and exchange data.

JsonSerializer.Serialize, in System.Text.Json, turns a value into JSON text. A list becomes an array in square brackets, and a record becomes an object with its property names. File.WriteAllText(path, text) creates the file, or replaces everything in it:

using System.Text.Json;

var scores = new List<int> { 12, 40 };
scores.Add(31);
var json = JsonSerializer.Serialize(scores);
File.WriteAllText("scores.json", json);
Console.WriteLine(json);

This prints [12,40,31], and scores.json holds the same text.

challenge icon

Challenge

Easy

Make add save the expense to expenses.json.

  1. Add using System.Text.Json; under the other using line.
  2. Above var count = 0;, declare var file = "expenses.json"; and an empty List<Expense> named expenses.
  3. In the add case, after you create expense, add it to expenses and write the whole list to file as JSON. Write it before the Added line, and only after the amount was parsed: add Lunch abc writes no file.

After dotnet run -- add Lunch 12.50 food, expenses.json holds:

[{"Name":"Lunch","Amount":12.50,"Category":"food"}]

The file keeps only the newest expense for now, because the list starts empty on every run. The next lesson reads the saved ones back first.

Try it: the terminal beside the editor already reads dotnet run -- add Lunch 12.50 food, so press Run: Added Lunch: 12.50 (food). The terminal shows what the program prints, not the files it writes, so Check opens expenses.json and expects the array above. It also runs add Lunch abc, which must leave no file.

Try it yourself

using System.Globalization;

var count = 0;
var total = 0m;

if (args.Length == 0)
{
    Console.WriteLine("Expense Tracker");
    Console.WriteLine($"{count} expenses");
    Console.WriteLine($"Total: {total:F2}");
}
else
{
    switch (args[0])
    {
        case "add":
            if (args.Length < 3)
            {
                Console.Error.WriteLine("Usage: add <name> <amount> [category]");
                return 1;
            }
            if (!decimal.TryParse(args[2], CultureInfo.InvariantCulture, out var amount))
            {
                Console.Error.WriteLine($"Invalid amount: {args[2]}");
                return 1;
            }
            var category = args.Length > 3 ? args[3] : "other";
            var expense = new Expense(args[1], amount, category);
            Console.WriteLine($"Added {expense.Name}: {expense.Amount:F2} ({expense.Category})");
            break;
        default:
            Console.Error.WriteLine($"Unknown command: {args[0]}");
            return 1;
    }
}
return 0;

All lessons in C# and .NET Basics