Recipe 12.2 · C#
Source-Generated Serialization
Problem
Reflection-based serialization is fast once warmed up, but the first call for each type pays to build its metadata. In a serverless function, a command-line tool or a container that scales from zero, that start-up cost shows up on every cold start. Trimmed and native AOT builds go further and cannot use reflection-based serialization at all.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: reflection at runtime, warm-up on every cold start
string json = JsonSerializer.Serialize(order);
Order? copy = JsonSerializer.Deserialize<Order>(json);
Nothing is wrong with this code in a long-running web app. It becomes a problem when start-up time matters or when you publish with trimming, where the linker removes the members the serializer was going to discover at runtime.
The improved recipe
Declare a JsonSerializerContext and list the types you serialize. The compiler generates the
metadata and the fast-path serialization code at build time.
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ImproveCode.Serialization;
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true)]
[JsonSerializable(typeof(Order))]
[JsonSerializable(typeof(List<Order>))]
public partial class AppJsonContext : JsonSerializerContext
{
}
using System.Collections.Generic;
using System.Text.Json;
namespace ImproveCode.Serialization;
public static class OrderJson
{
public static string Serialize(Order order) =>
JsonSerializer.Serialize(order, AppJsonContext.Default.Order);
public static Order? Deserialize(string json) =>
JsonSerializer.Deserialize(json, AppJsonContext.Default.Order);
public static List<Order>? DeserializeList(string json) =>
JsonSerializer.Deserialize(
json, AppJsonContext.Default.ListOrder);
}
How it works
The [JsonSerializable] attributes tell the source generator which root types to handle. It walks
each type's properties, generates a JsonTypeInfo<T> for every type it finds, and exposes them as
properties on AppJsonContext.Default: Order, ListOrder, OrderLine and so on. Passing a
JsonTypeInfo<T> to Serialize or Deserialize skips reflection completely.
[JsonSourceGenerationOptions] carries the settings. Starting from JsonSerializerDefaults.Web
and adding UseStringEnumConverter gives you the same wire format as JsonDefaults.Web from the
previous recipe, so the two can read each other's output.
Because the code is generated at compile time, you can open it. In Visual Studio expand
Dependencies, Analyzers, System.Text.Json.SourceGeneration. It is ordinary C#, which also makes
serialization bugs easier to step through.
Variations and pitfalls
- The class must be
partial. The generator fills in the other half. Forget the keyword and you get a compile error that points at the generator, not at your class. - Missing types fail at runtime. If you serialize a type the context does not list, you get a
NotSupportedExceptionor, worse, a silent fallback to reflection. In the project file, set<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>so the fallback is off and the mistake shows up in your first test. - ASP.NET Core. Register the context with minimal APIs so request and response bodies use it:
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default)); - Combining with shared options. If you want
JsonDefaultsand the generated metadata together, createnew JsonSerializerOptions(JsonDefaults.Web) { TypeInfoResolver = AppJsonContext.Default }once and keep it in a static field. - When not to bother. For an internal line-of-business web app that starts once a day, the gain is small. Use source generation for cold-start-sensitive hosts, trimmed or AOT publishing, and the few hot paths a profiler points at.