Source Generated JSON Serialization using fast path in ASP.NET Core
05/11/2024
In this post I explore how ASP.NET Core works together with the source generated JSON serializer. In .NET 8 the streaming JSON serialization can be enabled to use serialization-optimization mode with ASP.NET Core. However, using the default settings does not enable this fast-path. In this post I will explore how to enable the fast-path serialization by exploring the inner workings of JsonTypeInfo.cs
. For this post I use .NET 8 with the corresponding ASP.NET Core release.
The .NET 8 runtime comes with three built-in JSON serializer modes:
Reflection
Source generation (Metadata-based mode)
Source generation (Serialization-optimization mode)
Reflection mode is the default one. This mode is used when someone invokes JsonSerializer.(De)SerializeAsync
without additional arguments passed. Source Generation (Metadata-based mode) as the name suggests generates source code at compile time that contains the metadata that the Reflection would need to discover during its first invocation. This mode helps to enable JSON serialization in environments where reflection otherwise would not be possible, for example in case of AOT published applications. Source generation (Serialization-optimization mode) also generates code at compile time, but besides the metadata it also uses a generated fast-path method when serializing objects.