How to Use System.Text.Json Source Generation in C# and .NET
By default, JsonSerializer.Serialize() and JsonSerializer.Deserialize() in System.Text.Json inspect your C# classes at runtime using reflection. Reflection is convenient for quick prototypes, yet it adds cold-start latency, increases private memory usage, and breaks under IL trimming and Native AOT deployments where unused metadata is stripped at publish time. System.Text.Json source generation moves that work to compile time using a partial JsonSerializerContext class.
Editorial illustration: JsonSerializerContext generates JSON contract metadata and fast-path serialization code during compilation.
Summary
- As documented in Microsoft Learn’s
System.Text.Jsonsource generation guide, creating apartial classderiving fromJsonSerializerContextwith[JsonSerializable(typeof(T))]generates serialization code at compile time. - Per Microsoft Learn’s reflection vs. source generation comparison, source generation supports two modes: Metadata-based mode (populates JSON contract metadata at compile time) and Serialization-optimization (fast-path) mode (emits direct
Utf8JsonWritercalls for higher serialization throughput). - Passing
AppJsonContext.Default.OrderorAppJsonContext.Defaultexplicitly avoids reflection completely, enabling IL trimming and Native AOT compatibility. - Keep reflection for scenarios where types are unknown at compile time or where unsupported dynamic features are required.
Prerequisites: .NET Runtime & C# Source Generators
Before adding a JsonSerializerContext, note what belongs to the .NET SDK vs. your project setup:
.NETBCL (System.Text.Json.Serialization): Source generation was introduced in.NET 6and significantly expanded across.NET 8,.NET 9, and.NET 10(with ASP.NET Core Minimal APIs and Native AOT templates wired directly toJsonSerializerContext).- C# Language & IDE: Requires a C# 9+ compiler supporting Roslyn source generators (available in Visual Studio 2022/2026 and the .NET SDK CLI).
- Project Type: Works in console apps, class libraries, Worker Services, and ASP.NET Core Web APIs.
Step-by-step: Add JsonSerializerContext to a .NET app
1. Define your model and partial JsonSerializerContext
Create a partial class that inherits from JsonSerializerContext and annotate every root type you serialize or deserialize:
using System.Text.Json;
using System.Text.Json.Serialization;
public sealed record OrderSummary(int Id, string CustomerEmail, decimal Total);
[JsonSourceGenerationOptions(
WriteIndented = false,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(OrderSummary))]
[JsonSerializable(typeof(List<OrderSummary>))]
internal partial class AppJsonContext : JsonSerializerContext
{
}
At build time, the System.Text.Json source generator inspects OrderSummary and emits AppJsonContext.OrderSummary and AppJsonContext.ListOrderSummary properties returning JsonTypeInfo<T>.
2. Pass the generated JsonTypeInfo<T> or context to JsonSerializer
To make sure your code actually uses the generated code (and does not silently fall back to reflection), pass the strongly typed JsonTypeInfo<T> or JsonSerializerContext overload:
var order = new OrderSummary(1042, "dev@example.com", 149.90m);
// Uses compile-time source generation (trim-safe and AOT-ready)
string json = JsonSerializer.Serialize(order, AppJsonContext.Default.OrderSummary);
OrderSummary? parsed = JsonSerializer.Deserialize(
json,
AppJsonContext.Default.OrderSummary);
Notice that calling JsonSerializer.Serialize(order) without passing AppJsonContext.Default.OrderSummary still uses runtime reflection!
3. Wire it into ASP.NET Core Minimal APIs
In an ASP.NET Core Minimal API (Program.cs), register the context on ConfigureHttpJsonOptions:
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default);
});
Inserting AppJsonContext.Default at index 0 ensures ASP.NET Core resolves your known DTOs from compile-time metadata first.
Understanding the two source-generation modes
Per Microsoft Learn’s source-generation modes documentation:
- Metadata-based mode: Collects type metadata at compile time so
JsonSerializerdoes not run reflection on startup. Supports both serialization and deserialization, plusJsonSerializerOptionscustomizations. - Serialization-optimization (fast-path) mode: Generates specialized code that writes directly to
Utf8JsonWriter, boosting serialization throughput when default options or[JsonSourceGenerationOptions]match. Note that Microsoft Learn explicitly points out that fast-path deserialization is not currently available—deserialization uses the metadata-based path.
By default, [JsonSerializable] enables both modes where supported.
Common mistakes
- Calling
JsonSerializer.Serialize(obj)without passingAppJsonContext.Default.MyTypeoroptions. Simply having aJsonSerializerContextclass in your project does nothing unless your call sites pass it (or configureTypeInfoResolver). - Forgetting to register nested or collection root types. If you serialize
List<OrderSummary>orApiResponse<OrderSummary>directly, add[JsonSerializable(typeof(List<OrderSummary>))]on the context—not justOrderSummary. - Ignoring
[JsonSourceGenerationOptions]vs. runtimeJsonSerializerOptions. Fast-path code generation bakes options likeCamelCaseat compile time. If you construct a separatenew JsonSerializerOptions { PropertyNamingPolicy = ... }at runtime without aligning them,System.Text.Jsonmay fall back to metadata mode or throw if no matching resolver is attached. - Using source generation with unsupported dynamic types. If your app serializes arbitrary
dynamicobjects or runtime-loaded plugin types unknown at compile time, reflection mode (without Native AOT) remains the right tool.
If you are building high-throughput .NET services, pair source-generated JSON with using PeriodicTimer in background loops and C# 14 implicit Span<T> conversions.
Why this matters
In containerized ASP.NET Core APIs, serverless functions, and CLI tools, startup latency and memory footprint matter as much as peak throughput. Switching known DTOs to JsonSerializerContext cuts reflection overhead immediately and prepares your codebase for IL trimming and Native AOT whenever you decide to turn it on.
My Take
Even if you are not shipping Native AOT binaries yet, adding a single AppJsonContext for your API request/response DTOs is low-effort and pays off right away in cleaner startup times and compile-time visibility over what gets serialized. Keep reflection only for dynamic plugin or diagnostic payloads where types cannot be known ahead of time.
Conclusion
Create a partial class inheriting from JsonSerializerContext, annotate your root DTOs with [JsonSerializable], pass AppJsonContext.Default.<Type> (or register TypeInfoResolverChain) at every serialization call site, and verify your build with trimming/AOT analyzers enabled.