Skip to content

JSON with System.Text.Json

The Course
•
30 min study

JSON is the common format for saved data and web APIs. It's text, readable by people and by nearly every language. .NET's own library, System.Text.Json, converts objects to JSON (serializing) and back again (deserializing).

Round trip

JsonSerializer.Serialize turns an object into a string. Deserialize<T> does the reverse. Records work without any extra code, since the constructor's parameters match the JSON's property names. The using line brings in the namespace.

To JSON and back C#
#nullable enable

using System.Text.Json;

var book = new Book("Dune", 412, new[] { "sf", "classic" });

string json = JsonSerializer.Serialize(book);
Console.WriteLine(json);

Book? back = JsonSerializer.Deserialize<Book>(json);
Console.WriteLine(back?.Title);
Console.WriteLine(back?.Tags.Length);

record Book(string Title, int Pages, string[] Tags);
Check your prediction
Text
{"Title":"Dune","Pages":412,"Tags":["sf","classic"]}
Dune
2

Deserialize can return null, since the text might be the JSON literal null. That's why this example uses ?..

Options

JsonSerializerOptions control the format. Create one and reuse it, because each one builds up a cache. WriteIndented makes the output readable, and the Web defaults use camelCase names. An enum (Day 4) is written as its number unless you add a converter, and a name is sturdier if you later reorder the enum. Either way, check a loaded enum with Enum.IsDefined, because the file may hold a number that isn't one of its names.

Readable, stable output C#
#nullable enable

using System.Text.Json;
using System.Text.Json.Serialization;

var options = new JsonSerializerOptions
{
    WriteIndented = true,
    Converters = { new JsonStringEnumConverter() },
};

var task = new Job(1, Level.High);
string json = JsonSerializer.Serialize(task, options);
Console.WriteLine(json);
Console.WriteLine(JsonSerializer.Serialize(task));

Job? back = JsonSerializer.Deserialize<Job>(json, options);
Console.WriteLine(back == task);

enum Level { Low, High }

record Job(int Id, Level Level);
Check your prediction
Text
{
  "Id": 1,
  "Level": "High"
}
{"Id":1,"Level":1}
True

Bad data

Data from a file or the network can be wrong. Broken JSON throws JsonException. But a missing property often doesn't: the value just becomes its default. So JSON that parses isn't the same as valid data. You still need your own checks after loading, and the tracker's Load does this. required can tighten things a little.

What fails, and what doesn't C#
#nullable enable

using System.Text.Json;

foreach (string text in new[] { "{\"Title\":\"Dune\",\"Pages\":5}", "{\"Title\":\"Dune\"}", "{\"Pages\":5}", "{broken", "{\"Title\":\"Dune\",\"Pages\":\"five\"}" })
{
    try
    {
        Book? book = JsonSerializer.Deserialize<Book>(text);
        Console.WriteLine(book);
    }
    catch (JsonException)
    {
        Console.WriteLine("not valid");
    }
}

record Book(string Title, int Pages);
Check your prediction
Text
Book { Title = Dune, Pages = 5 }
Book { Title = Dune, Pages = 0 }
Book { Title = , Pages = 5 }
not valid
not valid

The third line is a warning sign: Title is declared as string, not string?, yet it holds null. Nullable types are compile-time promises, and data from outside hasn't made any.

Reading without a type

When you only need one or two values from a large document, or the shape varies, JsonDocument lets you walk the JSON directly. TryGetProperty avoids an exception if the name is missing.

Walk the document C#
using System.Text.Json;

string json = "{\"name\":\"Ana\",\"scores\":[3,5,8],\"extra\":{\"age\":30}}";

using JsonDocument document = JsonDocument.Parse(json);
JsonElement root = document.RootElement;

Console.WriteLine(root.GetProperty("name").GetString());
Console.WriteLine(root.GetProperty("scores").EnumerateArray().Sum(score => score.GetInt32()));
Console.WriteLine(root.GetProperty("extra").GetProperty("age").GetInt32());
Console.WriteLine(root.TryGetProperty("missing", out _));
Check your prediction
Text
Ana
16
30
False

Fix it: Every field came back empty

This reads JSON written by a web service, which uses camelCase names. Predict the output, then run it.

Every field came back empty C#
using System.Text.Json;

string json = """{"name":"Ana","age":36}""";
Person person = JsonSerializer.Deserialize<Person>(json)!;
Console.WriteLine($"[{person.Name}] {person.Age}");

record Person(string Name, int Age);
Check your prediction
Text
[] 0

There's no error at all. By default, names must match exactly, including case, so name doesn't fill Name, and properties that don't appear in the JSON keep their default values. Fix it so that it prints [Ana] 36.

Fix it

Use the Web defaults, which read and write camelCase names and match them without regard to case:

C#
using System.Text.Json;

string json = """{"name":"Ana","age":36}""";
Person person = JsonSerializer.Deserialize<Person>(json, new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
Console.WriteLine($"[{person.Name}] {person.Age}");

record Person(string Name, int Age);
Text
[Ana] 36

A silent mismatch is worse than an exception, so check loaded data, as this lesson's next section does. Create the options once and reuse them in real code.

Your turn

Exercise

Save and restore settings

Write a record Settings(string Theme, int FontSize, List<string> Recent). Write Save(Settings settings, string path) to write indented JSON, and Load(string path), which returns Settings?: null if the file is missing, the JSON is broken, or FontSize is outside 8 to 72, or Theme is null or blank.

Save some settings and print whether what you load equals them in Theme and FontSize, plus its Recent count. Then write these files by hand and show that Load returns null for each: not JSON at all; a FontSize of 1; no Theme. Finish with a missing file.

When it works, it prints:

Text
True
2
broken.json: True
small.json: True
blank.json: True
missing.json: True
Your workspace C#
#nullable enable

using System.Text.Json;

Console.WriteLine("Start here");
Hint 1: the idea

Two kinds of failure lead to null here: an exception while reading (catch those) and a value that parsed but breaks a rule (test those). Keep them apart.

Hint 2: a first step

Write the round trip for the good case first. Note that == on records compares a List by reference, so a whole-record comparison would be false; that's why the brief compares individual fields.

Show one solution
C#
#nullable enable

using System.Text.Json;

var saved = new Settings("dark", 14, new List<string> { "a.txt", "b.txt" });
Save(saved, "settings.json");

Settings? loaded = Load("settings.json");
Console.WriteLine(loaded?.Theme == saved.Theme && loaded?.FontSize == saved.FontSize);
Console.WriteLine(loaded?.Recent.Count);

File.WriteAllText("broken.json", "not json");
File.WriteAllText("small.json", "{\"Theme\":\"dark\",\"FontSize\":1,\"Recent\":[]}");
File.WriteAllText("blank.json", "{\"FontSize\":14,\"Recent\":[]}");

foreach (string path in new[] { "broken.json", "small.json", "blank.json", "missing.json" })
{
    Console.WriteLine($"{path}: {Load(path) is null}");
}

static void Save(Settings settings, string path)
{
    File.WriteAllText(path, JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true }));
}

static Settings? Load(string path)
{
    Settings? settings;
    try
    {
        settings = JsonSerializer.Deserialize<Settings>(File.ReadAllText(path));
    }
    catch (FileNotFoundException)
    {
        return null;
    }
    catch (JsonException)
    {
        return null;
    }
    if (settings is null || string.IsNullOrWhiteSpace(settings.Theme) || settings.FontSize is < 8 or > 72)
    {
        return null;
    }
    return settings;
}

record Settings(string Theme, int FontSize, List<string> Recent);
Text
True
2
broken.json: True
small.json: True
blank.json: True
missing.json: True

Load treats every way the file can be bad in the same place: missing, not JSON, JSON with a missing or empty theme, or a font size out of range. Each gives null, so the caller has one check to make. Deserializing doesn't validate: blank.json deserializes happily with a null Theme, which is why the checks after the try matter as much as the catch clauses.

Was this article helpful?

Your response is saved on this device.