JSON serialization is a fundamental part of modern .NET applications. Web APIs use it to return responses, mobile applications use it to exchange data with backend services, and background services use it to communicate with external systems.
In many applications, JSON serialization works without requiring much configuration.
For example, you can serialize an object using System.Text.Json:
var json = JsonSerializer.Serialize(customer);
The serializer examines the object's properties, determines their types, and converts the object into JSON.
This process is convenient, but it involves runtime metadata discovery. When an application handles a large number of serialization operations, uses trimming, or targets Native AOT, relying entirely on runtime reflection can introduce performance and compatibility challenges.
.NET provides source generation for System.Text.Json to address these concerns.
Instead of discovering serialization metadata at runtime, the compiler generates the required serialization code during compilation. The application can then use this generated code when serializing and deserializing objects.
Source generation can reduce startup overhead, reduce private memory usage, improve serialization throughput in supported scenarios, and make JSON serialization more suitable for applications that use Native AOT.
This article explains how source-generated JSON serialization works, how to configure it, how to use it in ASP.NET Core APIs, and what to consider before introducing it into an existing application.
Understanding JSON Serialization in .NET
Before looking at source generation, it is useful to understand how JSON serialization normally works.
Consider a simple customer model:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
An application can serialize an instance using System.Text.Json:
using System.Text.Json;
var customer = new Customer
{
Id = 101,
Name = "Rahul",
Email = "[email protected]"
};
var json = JsonSerializer.Serialize(customer);
Console.WriteLine(json);
The output is:
{
"Id": 101,
"Name": "Rahul",
"Email": "[email protected]"
}
Deserialization works in the opposite direction:
var customer = JsonSerializer.Deserialize<Customer>(json);
The serializer needs information about the type to perform these operations.
It needs to know:
- Which properties should be serialized.
- Which getters should be called.
- Which constructors can be used during deserialization.
- Which setters should receive incoming values.
- Whether custom serialization attributes are present.
- How configured naming policies and converters should be applied.
This information is called serialization metadata.
By default, System.Text.Json can discover this metadata at runtime using reflection. The metadata is cached so that the serializer does not need to perform the same discovery for every operation.
However, metadata discovery still has an initial cost, and reflection can create challenges for applications that need aggressive trimming or Native AOT compatibility.
Source generation moves much of this work to compile time.
What Is Source Generated JSON Serialization?
Source-generated JSON serialization uses a C# source generator to inspect the types declared for serialization and generate the corresponding serialization metadata or optimized serialization code.
The generated code becomes part of the compiled application.
Instead of asking the serializer to discover the structure of a customer object at runtime, the application uses metadata generated during compilation.
The general workflow looks like this:
C# Model Classes
|
v
JsonSerializerContext
|
v
System.Text.Json Source Generator
|
v
Generated Serialization Code
|
v
Application Compilation
|
v
JSON Serialization and Deserialization
The developer identifies the types that need JSON support by applying attributes to a class derived from JsonSerializerContext.
The compiler then generates the required implementation.
The most important types and attributes are:
| Type or attribute | Purpose |
|---|
JsonSerializerContext | Base class for a source-generated JSON context |
JsonSerializableAttribute | Identifies a type that needs generated JSON metadata |
JsonSourceGenerationOptionsAttribute | Configures source-generation and serializer options |
JsonTypeInfo<T> | Provides generated metadata for a specific type |
JsonSerializer | Performs serialization and deserialization |
The generated context provides strongly typed metadata that can be passed directly to JsonSerializer.
Creating Your First Source Generated JSON Context
Let's convert the earlier customer example to use source generation.
Step 1: Create a model
Start with a simple model:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
There is no need to change the model simply because source generation is being introduced.
Step 2: Create a JsonSerializerContext
Create a partial class that inherits from JsonSerializerContext.
using System.Text.Json.Serialization;
[JsonSerializable(typeof(Customer))]
internal partial class AppJsonContext : JsonSerializerContext
{
}
The [JsonSerializable] attribute tells the source generator to create serialization support for the Customer type.
The partial keyword is important because the source generator supplies the other part of the class during compilation.
The generated context exposes metadata for the declared type through its Default property.
For example:
AppJsonContext.Default.Customer
This property provides a JsonTypeInfo<Customer> instance.
Step 3: Serialize using generated metadata
Now use the generated metadata instead of relying on the default reflection-based overload.
var customer = new Customer
{
Id = 101,
Name = "Rahul",
Email = "[email protected]"
};
var json = JsonSerializer.Serialize(
customer,
AppJsonContext.Default.Customer);
Console.WriteLine(json);
The serializer receives the generated metadata directly.
It does not need to discover the Customer type structure through its normal reflection-based metadata path.
Step 4: Deserialize using generated metadata
The same context can be used for deserialization:
var json = """
{
"Id": 101,
"Name": "Rahul",
"Email": "[email protected]"
}
""";
var customer = JsonSerializer.Deserialize(
json,
AppJsonContext.Default.Customer);
The generated metadata describes how the JSON should be mapped back to the Customer object.
This is an important distinction: metadata-based source generation supports both serialization and deserialization.
Understanding the Two Source Generation Modes
System.Text.Json supports two source-generation modes.
They solve related but different performance problems.
Understanding the difference helps developers choose the correct configuration.
Metadata-based source generation
Metadata-based generation moves the process of collecting serialization metadata from runtime to compile time.
The source generator creates the metadata needed by the serializer.
The generated metadata can be used for:
- Serialization.
- Deserialization.
- Runtime serializer operations that require type metadata.
For example:
[JsonSerializable(typeof(Customer))]
internal partial class CustomerJsonContext : JsonSerializerContext
{
}
This context provides the metadata required for both serialization and deserialization.
Metadata-based generation is generally the best starting point when an application wants to remove runtime reflection dependencies from its JSON serialization workflow.
It is also important for Native AOT scenarios.
Serialization-optimization mode
The second mode is called serialization-optimization mode, also known as fast-path serialization.
Instead of generating only metadata, the source generator creates optimized serialization code that writes JSON directly using Utf8JsonWriter.
For example:
[JsonSourceGenerationOptions(
GenerationMode = JsonSourceGenerationMode.Serialization)]
[JsonSerializable(typeof(Customer))]
internal partial class CustomerJsonContext : JsonSerializerContext
{
}
The generated implementation can avoid some of the overhead associated with the general-purpose serializer.
This mode is particularly useful when an application frequently serializes objects and needs to improve serialization throughput.
However, there are important limitations.
Fast-path generation is for serialization, not deserialization. It also does not support every System.Text.Json customization.
When an unsupported feature is used, the serializer can fall back to metadata-based processing if the context also contains the required metadata.
For this reason, many applications benefit from generating both modes rather than selecting serialization optimization alone.
Comparing the two modes
| Capability | Metadata-based | Serialization optimization |
|---|
| Serialization | Supported | Supported |
| Deserialization | Supported | Not supported |
| Runtime metadata discovery | Not required for generated types | Not required for generated types |
| Optimized JSON writing | Uses general serializer implementation | Generates optimized writing code |
| Support for serializer features | Broader support | Some limitations |
| Native AOT suitability | Yes | Yes, for supported scenarios |
If the application needs both serialization and deserialization, metadata generation is essential.
If serialization throughput is a major concern, test the optimization mode with the application's actual models and serializer options.
Configuring Serialization Options at Compile Time
Applications frequently need consistent JSON naming conventions.
For example, a .NET API may expose camelCase property names even though its C# models use PascalCase.
The serializer can apply naming policies using JsonSerializerOptions.
With source generation, these settings can also be declared using JsonSourceGenerationOptionsAttribute.
Consider the following context:
using System.Text.Json.Serialization;
[JsonSourceGenerationOptions(
WriteIndented = true,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(Customer))]
internal partial class AppJsonContext : JsonSerializerContext
{
}
The configuration specifies:
WriteIndented = true to produce formatted JSON.PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase to convert property names to camelCase.
Now serialize a customer:
var customer = new Customer
{
Id = 101,
Name = "Rahul",
Email = "[email protected]"
};
var json = JsonSerializer.Serialize(
customer,
AppJsonContext.Default.Customer);
The output becomes:
{
"id": 101,
"name": "Rahul",
"email": "[email protected]"
}
The naming policy is part of the generated context configuration.
This is useful when multiple parts of an application must follow the same JSON contract.
Supporting Multiple Models in One Context
A real application usually has more than one model.
An API might expose customers, orders, products, payments, and authentication responses.
You do not need to create a separate context for every model.
You can register multiple types in one context.
Consider the following models:
public class CustomerResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
public class OrderResponse
{
public int OrderId { get; set; }
public decimal TotalAmount { get; set; }
public string Status { get; set; } = string.Empty;
}
public class ProductResponse
{
public int ProductId { get; set; }
public string ProductName { get; set; } = string.Empty;
}
Create a shared context:
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(CustomerResponse))]
[JsonSerializable(typeof(OrderResponse))]
[JsonSerializable(typeof(ProductResponse))]
internal partial class AppJsonContext : JsonSerializerContext
{
}
Each registered model gets generated metadata.
You can now serialize each model:
var customerJson = JsonSerializer.Serialize(
new CustomerResponse
{
Id = 101,
Name = "Rahul"
},
AppJsonContext.Default.CustomerResponse);
var orderJson = JsonSerializer.Serialize(
new OrderResponse
{
OrderId = 5001,
TotalAmount = 2500,
Status = "Completed"
},
AppJsonContext.Default.OrderResponse);
This approach works well for applications that have a defined set of API contracts.
Register collection types
If an application serializes collections, explicitly register the collection type when it is used as a root serialization type.
For example:
[JsonSerializable(typeof(List<CustomerResponse>))]
internal partial class AppJsonContext : JsonSerializerContext
{
}
You can then serialize a list:
var customers = new List<CustomerResponse>
{
new()
{
Id = 101,
Name = "Rahul"
},
new()
{
Id = 102,
Name = "Priya"
}
};
var json = JsonSerializer.Serialize(
customers,
AppJsonContext.Default.ListCustomerResponse);
The generated property name is based on the registered type.
Registering the root collection is particularly useful when the application needs to use that collection directly with a generated JsonTypeInfo instance.
The generator can also discover supported member types through the object graph of registered types.
Using Source Generation in ASP.NET Core Web APIs
Source generation is especially useful in APIs that serialize and deserialize JSON for many requests.
ASP.NET Core uses System.Text.Json for JSON handling in common Web API scenarios.
You can configure the application's JSON options to use a generated context.
Let's build a practical example.
Create the API response model
public class ProductResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public bool IsAvailable { get; set; }
}
Create the JSON context
using System.Text.Json.Serialization;
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(ProductResponse))]
[JsonSerializable(typeof(List<ProductResponse>))]
internal partial class ApiJsonContext : JsonSerializerContext
{
}
Register the context in Program.cs
For an ASP.NET Core application using controllers, configure the JSON serializer options:
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.TypeInfoResolverChain
.Add(ApiJsonContext.Default);
});
var app = builder.Build();
app.MapControllers();
app.Run();
The TypeInfoResolverChain allows the application to use the generated context as one of its metadata resolvers.
The order matters because the serializer checks resolvers in sequence and uses the first one that provides metadata for the requested type.
For a closed API contract, the generated context should cover the models that the API needs.
If other types are required, the application must provide an appropriate additional resolver or register the missing types.
Create a controller
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
var products = new List<ProductResponse>
{
new()
{
Id = 1,
Name = "Laptop",
Price = 75000,
IsAvailable = true
},
new()
{
Id = 2,
Name = "Keyboard",
Price = 2500,
IsAvailable = true
}
};
return Ok(products);
}
}
The controller does not need to call JsonSerializer.Serialize() directly.
ASP.NET Core uses its configured JSON serializer options when producing the response.
The generated context provides metadata for the registered response types.
This is useful because serialization configuration stays centralized rather than being repeated across controllers.
Using Source Generation With HttpClient
.NET applications frequently consume external APIs through HttpClient.
For example, a service may retrieve customer information from another application.
A common implementation looks like this:
var customer = await httpClient.GetFromJsonAsync<CustomerResponse>(
"api/customers/101");
This overload uses the serializer's configured behavior.
When an application needs to use source-generated metadata explicitly, use an overload that accepts JsonTypeInfo<T>.
For example:
var customer = await httpClient.GetFromJsonAsync(
"api/customers/101",
ApiJsonContext.Default.CustomerResponse);
The generated metadata is supplied directly.
You can also use source-generated metadata when sending JSON to another API:
var response = await httpClient.PostAsJsonAsync(
"api/customers",
new CustomerResponse
{
Id = 101,
Name = "Rahul"
},
ApiJsonContext.Default.CustomerResponse);
This approach is particularly useful in applications where both the client and server have known JSON contracts.
It can also help when building applications that need trimming or Native AOT compatibility.
Handling Enums in Source Generated JSON Serialization
By default, enums are generally serialized as numeric values.
Consider the following enum:
public enum OrderStatus
{
Pending,
Processing,
Completed,
Cancelled
}
And a response model:
public class OrderResponse
{
public int OrderId { get; set; }
public OrderStatus Status { get; set; }
}
Without additional configuration, the serialized JSON may look like this:
{
"orderId": 5001,
"status": 2
}
Some APIs prefer readable string values.
You can configure string enum conversion in the source-generation context:
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
UseStringEnumConverter = true)]
[JsonSerializable(typeof(OrderResponse))]
internal partial class OrderJsonContext : JsonSerializerContext
{
}
Now the JSON representation uses the enum name:
{
"orderId": 5001,
"status": "Completed"
}
This makes the JSON easier for external clients to understand.
For individual enum types, you can also use the appropriate JSON converter attribute.
Remember that changing an existing API from numeric enum values to string values changes its external JSON contract. Review compatibility with existing clients before introducing this change.
Handling Polymorphic Types
Some applications serialize objects that can have multiple derived types.
For example, a notification system might support email notifications and SMS notifications.
public abstract class Notification
{
public string Message { get; set; } = string.Empty;
}
public class EmailNotification : Notification
{
public string EmailAddress { get; set; } = string.Empty;
}
public class SmsNotification : Notification
{
public string PhoneNumber { get; set; } = string.Empty;
}
When using polymorphic serialization, the serializer needs to know which derived types are allowed.
You can configure this using JsonDerivedTypeAttribute and JsonPolymorphicAttribute.
[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(EmailNotification), "email")]
[JsonDerivedType(typeof(SmsNotification), "sms")]
public abstract class Notification
{
public string Message { get; set; } = string.Empty;
}
Register the base type and derived types in the context:
[JsonSerializable(typeof(Notification))]
[JsonSerializable(typeof(EmailNotification))]
[JsonSerializable(typeof(SmsNotification))]
internal partial class NotificationJsonContext : JsonSerializerContext
{
}
Now the application can serialize supported notification types using the generated context.
The JSON can include a discriminator:
{
"type": "email",
"message": "Your order has been shipped.",
"emailAddress": "[email protected]"
}
Explicitly declaring supported derived types is important for predictable serialization contracts.
Avoid relying on arbitrary runtime types when an application needs a closed, known set of JSON contracts.
Understanding Object Properties and Runtime Types
One area that requires special attention is the use of object in model definitions.
Consider this class:
public class ApiResponse
{
public bool Success { get; set; }
public object? Data { get; set; }
}
The Data property can hold different runtime types.
For example:
var response = new ApiResponse
{
Success = true,
Data = new CustomerResponse
{
Id = 101,
Name = "Rahul"
}
};
The source generator cannot automatically predict every possible runtime type that might be assigned to an object property.
If the application knows the possible types, register them explicitly.
[JsonSerializable(typeof(ApiResponse))]
[JsonSerializable(typeof(CustomerResponse))]
[JsonSerializable(typeof(OrderResponse))]
internal partial class ApiJsonContext : JsonSerializerContext
{
}
This provides generated metadata for the declared runtime types.
However, the serializer still needs a way to determine how the object property should be handled at runtime.
For flexible response contracts, consider using a strongly typed model, a known polymorphic hierarchy, or an explicitly designed JSON structure instead of unrestricted object properties.
This makes the serialization contract easier to understand and maintain.
Combining Multiple Source Generated Contexts
Large applications may have multiple modules with separate serialization requirements.
For example:
- A customer module has customer-related JSON models.
- An order module has order-related models.
- A payment module has payment-related models.
- An integration module has external API contracts.
Creating one large context for the entire application is not always desirable.
.NET allows multiple generated contexts to be combined using JsonTypeInfoResolver.Combine().
For example:
var options = new JsonSerializerOptions
{
TypeInfoResolver = JsonTypeInfoResolver.Combine(
CustomerJsonContext.Default,
OrderJsonContext.Default,
PaymentJsonContext.Default)
};
The serializer can now look for metadata in each registered context.
Starting with .NET 8, you can also use TypeInfoResolverChain to add or reorder resolvers:
var options = new JsonSerializerOptions();
options.TypeInfoResolverChain.Add(
CustomerJsonContext.Default);
options.TypeInfoResolverChain.Add(
OrderJsonContext.Default);
options.TypeInfoResolverChain.Add(
PaymentJsonContext.Default);
The resolver order is significant.
The serializer checks the configured resolvers and uses the first resolver that provides metadata for the requested type.
This design is useful in modular applications where each feature owns its own serialization contracts.
Using Source Generation With Native AOT
Native AOT compiles an application ahead of time rather than relying on the traditional runtime compilation model.
This can provide advantages such as faster startup, smaller deployment footprints in suitable scenarios, and reduced runtime dependencies.
However, Native AOT imposes restrictions on dynamic runtime behavior, particularly reflection patterns that cannot be determined during compilation.
JSON serialization is an important area to consider because System.Text.Json uses reflection by default when no explicit metadata is supplied.
Source generation provides a way to declare the serialization types during compilation.
For example:
[JsonSerializable(typeof(CustomerResponse))]
[JsonSerializable(typeof(OrderResponse))]
internal partial class ApiJsonContext : JsonSerializerContext
{
}
The generated metadata can then be used explicitly:
var json = JsonSerializer.Serialize(
customer,
ApiJsonContext.Default.CustomerResponse);
This makes the serialization dependency visible and helps the compiler generate the required code.
Disable reflection-based serialization
For applications that want to ensure they do not accidentally depend on reflection-based JSON serialization, you can disable the default reflection resolver.
Add the following property to the project file:
<PropertyGroup>
<JsonSerializerIsReflectionEnabledByDefault>
false
</JsonSerializerIsReflectionEnabledByDefault>
</PropertyGroup>
When reflection-based serialization is disabled, code that requires the default reflection resolver can fail with a descriptive exception.
This is useful because missing source-generated metadata becomes easier to identify during development and testing.
The setting is also useful outside Native AOT applications when a team wants to enforce explicit JSON contracts.
However, disabling reflection means every required serialization type must be covered by the configured metadata resolvers.
Review third-party libraries and framework integrations as well, because they may rely on JSON types that are not immediately obvious in your own application code.
Inspecting Generated Source Code
One advantage of source generation is that the generated code can be inspected.
This helps developers understand what the compiler produces and troubleshoot missing metadata.
In Visual Studio, generated source files can be inspected through the generated files view for the project.
You can also enable compiler-generated file output in the project file:
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
For example, you can specify an output directory:
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>
$(BaseIntermediateOutputPath)Generated
</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
The compiler writes generated files to the configured location.
This is useful when troubleshooting problems such as:
- A missing generated context property.
- An unsupported model member.
- An incorrectly configured serialization option.
- An unregistered runtime type.
- An unexpected serialization fallback.
Generated files are compiler output. They should not normally be edited manually because the source generator will recreate them during compilation.
Common Limitations and Problems
Source generation provides important advantages, but it is not a universal replacement for reflection in every scenario.
Developers should understand its limitations before migrating an existing application.
Forgetting to register a type
Consider the following model:
public class ProductResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
If the type is not registered in the generated context, the application cannot obtain generated metadata for it.
Add the registration:
[JsonSerializable(typeof(ProductResponse))]
internal partial class AppJsonContext : JsonSerializerContext
{
}
Review the complete object graph and explicitly register root types that the application serializes or deserializes.
Using unsupported serialization features in fast-path mode
Serialization optimization does not support every feature available in System.Text.Json.
If the application depends on a feature that is not supported by fast-path generation, the serializer may need to use metadata-based processing.
If metadata is not available, serialization can fail.
For this reason, metadata generation is often a useful fallback even when serialization optimization is enabled.
Using private members with source generation
Source generation has different accessibility limitations from reflection-based serialization.
For example, a model that depends on private properties or private accessors may work differently when moved to source generation.
In .NET 10 and earlier, source generation does not support private or protected members and accessors in the same way reflection can. Explicitly applying [JsonInclude] to inaccessible members or accessors can result in a NotSupportedException.
Review the accessibility of model members when migrating existing serialization code.
Using unrestricted runtime types
Models that use object or dynamically selected runtime types need additional attention.
The source generator cannot automatically generate metadata for every possible type that might appear at runtime.
Register known types explicitly or redesign the model around a well-defined contract.
Assuming source generation automatically improves every operation
Metadata-based generation primarily reduces metadata discovery overhead and reflection dependencies.
Serialization-optimization mode can improve serialization throughput, but the actual result depends on the model, JSON options, payload size, and workload.
Do not assume every API endpoint will become significantly faster simply because source generation has been enabled.
Measure the actual application.
Benchmarking Source Generation
Performance improvements should be measured rather than assumed.
A useful benchmark compares:
- Reflection-based serialization.
- Metadata-based source generation.
- Serialization-optimization mode.
Use the same model, input data, serializer options, and runtime configuration for each test.
For example, a simple BenchmarkDotNet benchmark can compare serialization paths.
using BenchmarkDotNet.Attributes;
using System.Text.Json;
[MemoryDiagnoser]
public class JsonSerializationBenchmark
{
private readonly CustomerResponse _customer = new()
{
Id = 101,
Name = "Rahul"
};
[Benchmark(Baseline = true)]
public string ReflectionSerialization()
{
return JsonSerializer.Serialize(_customer);
}
[Benchmark]
public string SourceGeneratedSerialization()
{
return JsonSerializer.Serialize(
_customer,
CustomerJsonContext.Default.CustomerResponse);
}
}
The generated context might look like this:
[JsonSerializable(typeof(CustomerResponse))]
internal partial class CustomerJsonContext : JsonSerializerContext
{
}
This basic benchmark compares the default serializer path with the generated metadata path.
For a more complete benchmark, create separate contexts for metadata-only and serialization-optimization modes, and use identical serializer options.
Measure:
- Operations per second.
- Average serialization time.
- Allocated bytes.
- Garbage collection activity.
- Application startup time.
- Published application size when trimming or Native AOT is involved.
Run benchmarks using realistic data.
A model containing two properties may not demonstrate the same behavior as a response containing hundreds of nested objects and collections.
Also test deserialization separately. Serialization-optimization mode does not provide fast-path deserialization.
Migrating an Existing Application to Source Generation
An existing application does not need to replace every JSON serialization call at once.
A gradual migration is usually easier to manage.
Start by identifying the models used most frequently in JSON operations.
For example:
- API request models.
- API response models.
- External service contracts.
- Message queue payloads.
- Cache serialization models.
- Configuration and persistence models.
Create a context for those types:
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(CustomerResponse))]
[JsonSerializable(typeof(OrderResponse))]
[JsonSerializable(typeof(PaymentResponse))]
internal partial class ApplicationJsonContext : JsonSerializerContext
{
}
Next, replace important serialization calls with generated metadata:
var json = JsonSerializer.Serialize(
customer,
ApplicationJsonContext.Default.CustomerResponse);
For deserialization:
var customer = JsonSerializer.Deserialize(
json,
ApplicationJsonContext.Default.CustomerResponse);
Then configure ASP.NET Core and other framework integrations to use the generated context where appropriate.
Finally, test all JSON contracts.
Pay particular attention to:
- Property naming.
- Null handling.
- Enum conversion.
- Custom converters.
- Polymorphic models.
- Required properties.
- Date and time formats.
- Unknown JSON properties.
- Third-party integrations.
A serialization change can affect external API contracts, so compatibility testing is important.
Production Best Practices
For production .NET applications, consider the following practices when adopting source-generated JSON serialization.
| Area | Recommended practice |
|---|
| Context design | Group related serialization models logically |
| Type registration | Register all required root serialization types |
| Serialization | Use generated JsonTypeInfo<T> metadata |
| Deserialization | Use metadata-based source generation |
| Performance | Enable fast-path generation when it provides measurable benefits |
| ASP.NET Core | Register generated contexts in JSON options |
| Native AOT | Prefer explicit generated metadata |
| Reflection | Consider disabling reflection defaults when appropriate |
| Polymorphism | Declare supported derived types explicitly |
| Runtime types | Avoid unrestricted object properties |
| Testing | Verify JSON contracts after migration |
| Benchmarking | Measure throughput, allocations, startup, and published size |
A few additional recommendations are worth considering.
First, treat serialization models as part of the application's contract. Avoid exposing internal database entities directly when dedicated request and response models provide a more stable API.
Second, keep JSON contexts organized. A large application may benefit from separate contexts for API responses, external integrations, and messaging contracts.
Third, avoid generating optimized serialization code for every type without measuring its impact. Metadata generation may be sufficient for many applications.
Finally, keep the generated metadata configuration consistent with the serializer options used at runtime. Unexpected differences between contexts and runtime options can lead to confusing serialization behavior.
Conclusion
Source-generated JSON serialization is a useful capability for modern .NET applications that need predictable serialization behavior, lower runtime metadata overhead, and better compatibility with trimming and Native AOT.
By using JsonSerializerContext and JsonSerializableAttribute, developers can declare the types that require JSON support and let the compiler generate the required metadata.
The two source-generation modes serve different purposes. Metadata-based generation supports both serialization and deserialization, while serialization-optimization mode generates faster writing code for supported scenarios.
For ASP.NET Core APIs, the generated context can be registered in JSON options so that controllers use the generated metadata without manually serializing every response.
However, source generation requires deliberate type registration and attention to polymorphism, custom converters, runtime types, and accessibility limitations.
The best approach is to start with frequently used JSON contracts, introduce generated metadata, verify compatibility, and benchmark the results under realistic workloads.
This gives .NET applications a more predictable serialization model while preparing them for performance-sensitive deployments and Native AOT scenarios.
Join the conversation! Your thoughts help the community grow.