How to choose reflection or source generation in System.Text.Json
By default, System.Text.Json uses run-time reflection to gather the metadata it needs to access properties of objects for serialization and deserialization. As an alternative, System.Text.Json 6.0 and later can use the C# source generation feature to improve performance, reduce private memory usage, and facilitate assembly trimming, which reduces app size.
You can use version 6.0+ of System.Text.Json in projects that target earlier frameworks. For more information, see How to get the library.
This article explains the options and provides guidance on how to choose the best approach for your scenario.
Overview
Choose reflection or source generation modes based on the following benefits that each one offers:
| Benefit | Reflection | Source generation: Metadata collection |
Source generation: Serialization optimization |
|---|---|---|---|
| Simpler to code and debug. | ✔️ | ❌ | ❌ |
| Supports non-public accessors. | ✔️ | ❌ | ❌ |
| Supports required properties. | ✔️ | ✔️ | ✔️ |
| Supports init-only properties. | ✔️ | ✔️ | ✔️ |
| Supports all available serialization customizations. | ✔️ | ❌ | ❌ |
| Reduces start-up time. | ❌ | ✔️ | ❌ |
| Reduces private memory usage. | ❌ | ✔️ | ✔️ |
| Eliminates run-time reflection. | ❌ | ✔️ | ✔️ |
| Facilitates trim-safe app size reduction. | ❌ | ✔️ | ✔️ |
| Increases serialization throughput. | ❌ | ❌ | ✔️ |
| Benefit | Reflection | Source generation: Metadata collection |
Source generation: Serialization optimization |
|---|---|---|---|
| Simpler to code and debug. | ✔️ | ❌ | ❌ |
| Supports non-public accessors. | ✔️ | ❌ | ❌ |
| Supports required properties. | ✔️ | ❌ | ❌ |
| Supports init-only properties. | ✔️ | ❌ | ❌ |
| Supports all available serialization customizations. | ✔️ | ❌ | ❌ |
| Reduces start-up time. | ❌ | ✔️ | ❌ |
| Reduces private memory usage. | ❌ | ✔️ | ✔️ |
| Eliminates run-time reflection. | ❌ | ✔️ | ✔️ |
| Facilitates trim-safe app size reduction. | ❌ | ✔️ | ✔️ |
| Increases serialization throughput. | ❌ | ❌ | ✔️ |
The following sections explain these options and their relative benefits.
System.Text.Json metadata
To serialize or deserialize a type, JsonSerializer needs information about how to access the members of the type. JsonSerializer needs the following information:
- How to access property getters and fields for serialization.
- How to access a constructor, property setters, and fields for deserialization.
- Information about which attributes have been used to customize serialization or deserialization.
- Run-time configuration from JsonSerializerOptions.
This information is referred to as metadata.
By default, JsonSerializer collects metadata at run time by using reflection. Whenever JsonSerializer has to serialize or deserialize a type for the first time, it collects and caches this metadata. The metadata collection process takes time and uses memory.
Source generation - metadata collection mode
You can use source generation to move the metadata collection process from run time to compile time. During compilation, the metadata is collected and source code files are generated. The generated source code files are automatically compiled as an integral part of the application. This technique eliminates run-time metadata collection, which improves performance of both serialization and deserialization.
The performance improvements provided by source generation can be substantial. For example, test results have shown up to 40% or more startup time reduction, private memory reduction, throughput speed increase (in serialization optimization mode), and app size reduction.
Known issues
Only public properties and fields are supported by default* in either serialization mode. However, reflection mode supports the use of private accessors, while source-generation mode doesn't. For example, you can apply the JsonInclude attribute to a property that has a private setter or getter and it will be serialized in reflection mode. Source-generation mode supports only public or internal accessors of public properties. If you set [JsonInclude] on non-public accessors and choose source-generation mode, a NotSupportedException will be thrown at run time.
Only public properties and fields are supported by default* in either serialization mode. However, reflection mode supports the use of private members and private accessors, while source-generation mode doesn't. For example, if you apply the JsonInclude attribute to a private property or a property that has a private setter or getter, it will be serialized in reflection mode. Source-generation mode supports only public or internal members and public or internal accessors of public properties. If you set [JsonInclude] on private members or accessors and choose source-generation mode, a NotSupportedException will be thrown at run time.
For information about other known issues with source generation, see the GitHub issues that are labeled "source-generator" in the dotnet/runtime repository.
Serialization optimization mode
JsonSerializer has many features that customize the output of serialization, such as camel-casing property names and preserving references. Support for all those features causes some performance overhead. Source generation can improve serialization performance by generating optimized code that uses Utf8JsonWriter directly.
The optimized code doesn't support all of the serialization features that JsonSerializer supports. The serializer detects whether the optimized code can be used and falls back to default serialization code if unsupported options are specified. For example, JsonNumberHandling.AllowReadingFromString is not applicable to writing, so specifying this option doesn't cause a fall-back to default code.
The following table shows which options in JsonSerializerOptions are supported by the optimized serialization code:
| Serialization option | Supported by optimized code |
|---|---|
| Converters | ❌ |
| DefaultIgnoreCondition | ✔️ |
| DictionaryKeyPolicy | ❌ |
| Encoder | ❌ |
| IgnoreNullValues | ❌ |
| IgnoreReadOnlyFields | ✔️ |
| IgnoreReadOnlyProperties | ✔️ |
| IncludeFields | ✔️ |
| NumberHandling | ❌ |
| PropertyNamingPolicy | ✔️ |
| ReferenceHandler | ❌ |
| TypeInfoResolver | ✔️ |
| WriteIndented | ✔️ |
The following table shows which attributes are supported by the optimized serialization code:
| Attribute | Supported by optimized code |
|---|---|
| JsonConverterAttribute | ❌ |
| JsonDerivedTypeAttribute | ✔️ |
| JsonExtensionDataAttribute | ❌ |
| JsonIgnoreAttribute | ✔️ |
| JsonIncludeAttribute | ✔️ |
| JsonNumberHandlingAttribute | ❌ |
| JsonPolymorphicAttribute | ✔️ |
| JsonPropertyNameAttribute | ✔️ |
| JsonRequiredAttribute | ✔️ |
If a non-supported option or attribute is specified for a type, the serializer falls back to the default JsonSerializer code. In that case, the optimized code isn't used when serializing that type but may be used for other types. Therefore it's important to do performance testing with your options and workloads to determine how much benefit you can actually get from serialization optimization mode. Also, the ability to fall back to JsonSerializer code requires metadata collection mode. If you select only serialization optimization mode, serialization might fail for types or options that need to fall back to JsonSerializer code.
How to use source generation modes
Most of the System.Text.Json documentation shows how to write code that uses reflection mode. For information about how to use source generation modes, see How to use source generation in System.Text.Json.
Serialize enum fields as strings
JsonStringEnumConverter<T> converter
By default, enums are serialized as numbers. To serialize enum names as strings using source generation, use the JsonStringEnumConverter<TEnum> converter. (The non-generic JsonStringEnumConverter type is not supported by the Native AOT runtime.)
Suppose you need to serialize the following class that has an enum property:
public class WeatherForecastWithPrecipEnum
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public Precipitation? Precipitation { get; set; }
}
[JsonConverter(typeof(JsonStringEnumConverter<Precipitation>))]
public enum Precipitation
{
Drizzle, Rain, Sleet, Hail, Snow
}
Create a JsonSerializerContext class and annotate it with the JsonSerializableAttribute attribute:
[JsonSerializable(typeof(WeatherForecastWithPrecipEnum))]
public partial class Context1 : JsonSerializerContext { }
The following code serializes the enum names instead of the numeric values:
var weatherForecast = new WeatherForecastWithPrecipEnum
{
Date = DateTime.Parse("2019-08-01"),
TemperatureCelsius = 25,
Precipitation = Precipitation.Sleet
};
var options = new JsonSerializerOptions
{
WriteIndented = true,
TypeInfoResolver = Context1.Default,
};
string? jsonString = JsonSerializer.Serialize(weatherForecast, options);
The resulting JSON looks like the following example:
{
"Date": "2019-08-01T00:00:00-07:00",
"TemperatureCelsius": 25,
"Precipitation": "Sleet"
}
Blanket policy
Instead of using the JsonStringEnumConverter<TEnum> type, you can apply a blanket policy to serialize enums as strings by using the JsonSourceGenerationOptionsAttribute. Create a JsonSerializerContext class and annotate it with the JsonSerializableAttribute and JsonSourceGenerationOptionsAttribute attributes:
[JsonSourceGenerationOptions(UseStringEnumConverter = true)]
[JsonSerializable(typeof(WeatherForecast2WithPrecipEnum))]
public partial class Context2 : JsonSerializerContext { }
Notice that the enum doesn't have the JsonConverterAttribute:
public class WeatherForecast2WithPrecipEnum
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public Precipitation2? Precipitation { get; set; }
}
public enum Precipitation2
{
Drizzle, Rain, Sleet, Hail, Snow
}
See also
.NET feedback
The .NET documentation is open source. Provide feedback here.
Feedback
Submit and view feedback for