[Breaking change]: System.Text.Json source generator no longer fall backs to reflection-based serialization #30755
Closed
1 of 2 tasks
Labels
binary incompatible
Existing binaries may encounter a breaking change in behavior.
breaking-change
Indicates a .NET Core breaking change
🏁 Release: .NET 7
Work items for the .NET 7 release
doc-idea
Indicates issues that are suggestions for new topics [org][type][category]
Pri1
High priority, do before Pri2 and Pri3
Description
Starting with .NET 7 Preview 7, the System.Text.Json source generator will no longer implicitly fall back to reflection-based serialization for unrecognized types, when using one of the
JsonSerializer
methods acceptingJsonSerializerOptions
.Version
.NET 7 Preview 7
Previous behavior
Consider the following source gen example in .NET 6:
Since
MyContext
does not includePoco2
in its serializable types, the above will fail with the following exception:Note however that if we try to serialize the same type using the
JsonSerializerOptions
instance constructed by the source generator:The options instance will silently incorporate the default reflection-based contract resolver as a fallback mechanism, and as such the above will serialize successfully -- using reflection.
New behavior
Using the above example, the statement
Should fail with the same exception as using the
JsonSerializerContext
overload.The same fallback logic applies to
JsonSerializerOptions.GetConverter
for options instances attached to aJsonSerializerContext
. The following statementwill return a converter using the built-in reflection converter. In .NET 7 this will start failing with
NotSupportedException
.Type of breaking change
Reason for change
We believe that the existing behavior violates the principle of least surprise and ultimately defeats the purpose of source generation. With the release of dotnet/runtime#63686 users will have the ability to fine tune the sources of their contract metadata -- as such silently introducing alternative sources becomes even less desirable.
Recommended action
We acknowledge that certain users might depend on the current behavior, either intentionally or unintentionally. As such, we propose the following workaround using the APIs released in dotnet/runtime#63686:
Feature area
Core .NET libraries
Affected APIs
No response
The text was updated successfully, but these errors were encountered: