IntermediateLesson 13 of 205 min read

Files and JSON: Saving and Loading Data

Learn to read and write text files, serialise records to JSON with System.Text.Json, load them back, handle a missing file and malformed JSON, with the JSON text checked by an independent parser.

In this lesson you will

  • Write and read text files
  • Serialise and deserialise JSON
  • Handle missing files and bad JSON
  • Verify the data with a second parser

About 28 minutes

Orders that survive a restart

Until now Omar’s orders lived in memory and vanished when the program ended. Saving them to a file is the first step towards a real application. .NET has two helpers that cover most needs. The File class reads and writes text in one call, with methods like WriteAllText, ReadAllText and AppendAllText, and Path builds file names that work on every operating system. For structured data, System.Text.Json turns objects into JSON text and back again, with JsonSerializer.Serialize and Deserialize. JSON is a plain text format, made of objects in curly braces, arrays in square brackets, text in quotes and numbers, and nearly every language and web service can read it.

Need Call
Temporary folder Path.Combine(Path.GetTempPath(), name)
Write text File.WriteAllText(path, text)
Read text File.ReadAllText(path)
Append a line File.AppendAllText(path, line)
Object to JSON JsonSerializer.Serialize(obj)
JSON to object JsonSerializer.Deserialize(json)

Records work well with JSON because they are plain data. Serialisation uses the property names, and the default options keep their case, so a property Name becomes “Name” unless you ask for camel case. Failures are ordinary exceptions: a missing file throws FileNotFoundException or DirectoryNotFoundException, and text that is not valid JSON throws JsonException with a message that includes the line and position, which is handy for finding the problem.

using System.Text.Json;
var orders = new List<Order> { new("Ana", "latte", 2, 3.20m), new("Ben", "cake", 1, 3.50m), new("Cy", "tea", 3, 2.10m) };
string json = JsonSerializer.Serialize(orders);
Console.WriteLine(json);
string dir = Path.Combine(Path.GetTempPath(), "omar_" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(dir);
string file = Path.Combine(dir, "orders.json");
File.WriteAllText(file, json);
Console.WriteLine($"file exists: {File.Exists(file)}, size: {new FileInfo(file).Length} bytes, characters in text: {json.Length}");
var back = JsonSerializer.Deserialize<List<Order>>(File.ReadAllText(file))!;
Console.WriteLine($"read back {back.Count} orders, same as original: {back.SequenceEqual(orders)}");
Console.WriteLine($"total: {back.Sum(o => o.Qty * o.Price)}");
File.AppendAllText(Path.Combine(dir, "log.txt"), "first line\n");
File.AppendAllText(Path.Combine(dir, "log.txt"), "second line\n");
Console.WriteLine($"log has {File.ReadAllLines(Path.Combine(dir, "log.txt")).Length} lines");
try { File.ReadAllText(Path.Combine(dir, "missing.json")); }
catch (FileNotFoundException) { Console.WriteLine("FileNotFoundException for the missing file"); }
try { JsonSerializer.Deserialize<List<Order>>("[{\"Customer\": \"Ana\", "); }
catch (JsonException e) { Console.WriteLine($"JsonException: {e.Message.Split('.')[0]}"); }
var pretty = JsonSerializer.Serialize(orders[0], new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
Console.WriteLine(pretty);
Directory.Delete(dir, true);
Console.WriteLine($"cleaned up: {!Directory.Exists(dir)}");

record Order(string Customer, string Item, int Qty, decimal Price);
[{"Customer":"Ana","Item":"latte","Qty":2,"Price":3.20},{"Customer":"Ben","Item":"cake","Qty":1,"Price":3.50},{"Customer":"Cy","Item":"tea","Qty":3,"Price":2.10}]
file exists: True, size: 162 bytes, characters in text: 162
read back 3 orders, same as original: True
total: 16.20
log has 2 lines
FileNotFoundException for the missing file
JsonException: Expected start of a property name or value, but instead reached end of data
{
  "customer": "Ana",
  "item": "latte",
  "qty": 2,
  "price": 3.20
}
cleaned up: True

The first line of the output is the JSON text, 162 characters long. To check it with a second, independent parser, the course loaded it in Python, which found 3 objects, the first with Customer “Ana”, Item “latte”, Qty 2 and Price 3.2, exactly the data we serialised. The file on disk has 162 bytes, equal to the number of characters, since all of them are plain ASCII. Reading it back gave 3 orders, and the records compare equal to the originals, because records have value equality, so a round trip lost nothing. The total, 16.20, is 2 x 3.20 + 3.50 + 3 x 2.10.

The error cases are real exceptions. The missing file gave a FileNotFoundException, and the truncated JSON gave a JsonException whose message starts “Expected start of a property name or value, but instead reached end of data”, which is the part to read when your data will not parse. The indented version with camel case shows how options change the shape of the text, which matters when another system expects a particular style. At the end the program deleted its temporary folder, and confirmed it was gone, because tests and demos should clean up after themselves.

Check by hand: 2 x 3.20 = 6.40, plus 3.50, plus 3 x 2.10 = 6.30, makes 16.20, which is the total printed.

Why JSON is so common

JSON became the default way to exchange data because it is plain text that people can read, it maps naturally to objects, lists and values in almost every language, and the tools for it are built into the platform. That portability is the reason that the check in this lesson used a different language to read the file: if a Python script can read what C# wrote, so can a web page, a mobile app or a database. The cost is that JSON has no comments, no dates and no distinction between integers and decimals, so agree with the other side on how those are written, for example dates as ISO 8601 text.

Never trust a file to be there or to be valid

Handle FileNotFoundException and JsonException where you read data, and decide what the program does: stop with a message, use defaults or ask the user.

Use Path.Combine and temporary folders

Path.Combine builds paths that work on every system, and Path.GetTempPath gives a safe place for experiments and tests.

About this course

Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8.

Practice

Save a list of menu items to a JSON file and load it at the start of a program. Add a version number to the file and refuse files with an unknown version. Write a second program in another language that reads the same file, to see how portable JSON is.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Which class serialises objects to JSON in .NET?

  1. Path
  2. JsonSerializer
  3. Console
  4. Task

It lives in System.Text.Json.

Why did the record round trip compare equal?

  1. Records have value equality
  2. Files never change data
  3. The compiler cheated
  4. Equality is always true

Same property values.

Which exception means the file is missing?

  1. FileNotFoundException
  2. FormatException
  3. NullReferenceException
  4. OverflowException

Also DirectoryNotFoundException for folders.

How was the JSON checked independently?

  1. By reading it twice
  2. By its length only
  3. It was not
  4. By parsing it in Python

Same objects, same values.

Why use Path.Combine?

  1. It speeds up the program
  2. It encrypts the path
  3. It creates folders
  4. It builds paths that work on every system

No hand-made slashes.

Summary

  • File and Path read, write and locate files.
  • JsonSerializer turns objects into JSON and back.
  • Missing files and bad JSON are ordinary exceptions to handle.
  • An independent parser verified the JSON.

Next lesson

Lesson 14 covers async and await: doing several things at once.

Questions

Can System.Text.Json handle my own classes?

Yes. Public properties are serialised by default, and attributes and options let you control names and ignored fields.

What about large files?

For big files, stream with File.OpenRead and JsonSerializer.DeserializeAsync, or read line by line with File.ReadLines.

Is JSON the only choice?

No. XML, CSV and binary formats exist. JSON is a popular default for readable, portable data.

Progress is saved in this browser.