Menu
CoddyTech

Loading JSON

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

Reading JSON back is the reverse of saving it. File.ReadAllText(path) returns the file's text, and JsonSerializer.Deserialize<T>(text) builds a value of type T from it. Reading a file that does not exist throws an exception, so check with File.Exists first.

var scores = new List<int>();
if (File.Exists("scores.json"))
{
    scores = JsonSerializer.Deserialize<List<int>>(File.ReadAllText("scores.json")) ?? new List<int>();
}

Deserialize returns null when the file holds the JSON null, so its type is List<int>?. The ?? operator uses the right side when the left is null. The property names must match the record's exactly, Name and not name, or that property is left null or 0.

scores.Sum() adds up a list of numbers, and expenses.Sum(e => e.Amount) adds up one number from each item. The LINQ chapter covers this form.

challenge icon

Challenge

Easy

Your project now has an expenses.json with three saved expenses. Load them when the program starts.

  1. Right after var expenses = new List<Expense>();, when File.Exists(file), replace expenses with the list read from the file. Use ?? new List<Expense>() for a file that holds null.
  2. Set count to expenses.Count and total to the sum of the amounts, expenses.Sum(e => e.Amount).

With the three expenses in expenses.json, dotnet run prints:

Expense Tracker
3 expenses
Total: 48.50

add now adds to the saved list, so after add Taxi 23.40 travel the file holds four expenses.

Try it: the terminal beside the editor has no arguments after dotnet run --, so press Run: you see the three lines above. Then add a fourth expense to expenses.json, such as { "Name": "Book", "Amount": 9.50, "Category": "fun" } after a comma, and Run again: 4 expenses and Total: 58.00. Each Run starts again from the files in the editor, so what add saves is gone on the next Run: Check runs add Taxi 23.40 travel and reads the file right after it.

Try it yourself

using System.Globalization;
using System.Text.Json;

var file = "expenses.json";
var expenses = new List<Expense>();
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);
            expenses.Add(expense);
            File.WriteAllText(file, JsonSerializer.Serialize(expenses));
            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