Recipe 12.1 · C#
System.Text.Json Options Done Once
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
You serialize and deserialize JSON in a dozen places. Each call site passes its own options, or no
options at all, so one endpoint writes customerName and another writes CustomerName. Enums go
out as numbers. Reads from a partner fail because they send "42" where you expected 42. And a
profiler shows serialization taking far more time than it should.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: new options on every call, settings drift per call site
public static class JsonUtil
{
public static string ToJson(object value)
{
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
return JsonSerializer.Serialize(value, options);
}
public static T FromJson<T>(string json)
{
return JsonSerializer.Deserialize<T>(json); // case-sensitive
}
}
Two problems hide here. ToJson and FromJson disagree: one writes camelCase, the other reads
with the default case-sensitive, PascalCase rules, so a round trip through this class loses every
property. And each new JsonSerializerOptions starts with an empty metadata cache. The serializer
has to reflect over your types again on every call. On a busy API that alone can cost more than
the actual work.
The improved recipe
Create the options once, freeze them, and share them. The listing below defines the model used in
this chapter and a JsonDefaults class with two shared instances.
using System;
using System.Collections.Generic;
namespace ImproveCode.Serialization;
public enum OrderStatus { Pending, Shipped, Cancelled }
public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice);
public sealed class Order
{
public required int Id { get; init; }
public required string CustomerName { get; init; }
public DateTimeOffset PlacedAt { get; init; }
public OrderStatus Status { get; init; }
public string? Notes { get; init; }
public List<OrderLine> Lines { get; init; } = [];
}
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ImproveCode.Serialization;
public static class JsonDefaults
{
/// <summary>camelCase, case-insensitive reads, enums as strings.
/// </summary>
public static JsonSerializerOptions Web { get; } = CreateWeb();
/// <summary>Same as Web, but indented for files and logs.</summary>
public static JsonSerializerOptions Indented { get; } =
Freeze(new JsonSerializerOptions(Web) { WriteIndented = true });
private static JsonSerializerOptions CreateWeb()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
options.Converters.Add(new JsonStringEnumConverter());
return Freeze(options);
}
private static JsonSerializerOptions Freeze(
JsonSerializerOptions options)
{
options.MakeReadOnly(populateMissingResolver: true);
return options;
}
}
A small file helper on top keeps call sites short:
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace ImproveCode.Serialization;
public static class JsonFile
{
public static async Task<T> ReadAsync<T>(
string path, CancellationToken ct = default)
{
await using FileStream stream = File.OpenRead(path);
T? value = await JsonSerializer.DeserializeAsync<T>(
stream, JsonDefaults.Web, ct);
return value ?? throw new InvalidDataException(
$"'{path}' contained JSON null.");
}
public static async Task WriteAsync<T>(
string path, T value, CancellationToken ct = default)
{
await using FileStream stream = File.Create(path);
await JsonSerializer.SerializeAsync(
stream, value, JsonDefaults.Indented, ct);
}
}
How it works
JsonSerializerDefaults.Web turns on the three settings almost every API wants: camelCase names,
case-insensitive property matching on read, and numbers accepted when they arrive as quoted
strings. That last one is what fixes the partner who sends "42". On top of that I skip nulls on
write, tolerate comments and trailing commas in hand-edited files, and write enums as their names.
MakeReadOnly(populateMissingResolver: true) freezes the instance and attaches the default
reflection resolver. A frozen options object can be shared across threads with no risk that some
call site changes a setting for everyone else. Any attempt to modify it throws, which is exactly
what you want to find in a code review.
The metadata cache lives on the options instance. Because Web and Indented are created once,
the serializer reflects over Order once per process, not once per call.
The Order class uses required members. Since .NET 8 the serializer honors required: if the
JSON has no id or customerName, deserialization fails with a JsonException naming the missing
property instead of handing you an object with a zero ID.
Variations and pitfalls
- Enums as strings protect stored data. If you persist JSON and someone inserts a value in the middle of an enum, every number after it now means something else. Names survive reordering.
- Coming from Newtonsoft.Json.
[JsonProperty]and[JsonIgnore]fromNewtonsoft.Jsonare silently ignored bySystem.Text.Json. Use[JsonPropertyName]and theJsonIgnorefromSystem.Text.Json.Serialization. Fields are not serialized unless you setIncludeFields, and non-public setters need[JsonInclude]. - Reference loops. Entity graphs with back references (
Order.Customer.Orders) throw by default. SetReferenceHandler = ReferenceHandler.IgnoreCycles, or better, serialize a DTO. - .NET 9 additions.
JsonSerializerOptions.Webis a ready-made frozen instance, andRespectNullableAnnotations = truemakes the serializer rejectnullfor non-nullable reference properties. Turn the second one on for new code. - Atomic writes.
JsonFile.WriteAsyncoverwrites in place. For files another process reads, write to a temporary file and move it, as shown in Chapter 10.
On .NET Framework
System.Text.Json ships as a NuGet package for .NET Framework 4.6.2 and later, and the code above
works there with the System.Text.Json package installed. If the app is already full of
Newtonsoft.Json, apply the same discipline: one static JsonSerializerSettings, created once.