Author: | mphilipp622 |
---|---|
Assignees: | - |
Labels: | `area-System.Text.Json` |
Milestone: | - |
Closed mphilipp622 closed 1 year ago
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis See info in area-owners.md if you want to be subscribed.
Author: | mphilipp622 |
---|---|
Assignees: | - |
Labels: | `area-System.Text.Json` |
Milestone: | - |
This is by design -- any type passed to the source generator (including generic instantiations) must be specified explicitly via the JsonSerializable
attribute. This is because generating metadata for generic instantiations or types deriving from what has been declared always requires reflection that is not supported in trimmed/NativeAOT applications, which is the key use case for source generators. If your code doesn't use trimming or NativeAOT, you can avoid the need to explicitly declare every type by using the reflection-based serializer.
Description
In dotnet 7 System.Text.Json source generation, the fallback breaking change is effecting
IEnumerable
types that are not explicitly declared. E.G: an ASP.NET Core web api controller returnsIEnumerable<MyType>
and the source generator declares[JsonSerializable(typeof(IEnumerable<MyType>))]
. The source generator fails when returning aList<MyType>
because theList<MyType>
is not explicitly declared in the source generator.Does this mean that anywhere that I am passing a type that implements
IEnumerable
, I have to explicitly declare it in the source generator? If this is intentional, then it seems to make using the built-in C# interface types less flexible. I know dotnet7 introduced polymorphic serialization/deserialization. Does this mean I need to implement polymorphic serialization/deserialization of IEnumerable on my own? Is this not provided by the library out of the box?Reproduction Steps
I created a new Console app using dotnet 7. In the top-level Program.cs file:
Expected behavior
Successful response with following payload:
Actual behavior
Regression?
This worked in dotnet 6. Dotnet 7 introduced the breaking change for the source generator fallback, as specified here.
Known Workarounds
As per the breaking change article, I understand you can re-enable the reflection-based fallback globally. However, I still think having a solution for commonly used built-in interfaces, like
IEnumerable
, would be beneficial.Configuration
.NET Version: 7.0 OS: Windows 11 Architecture: x64 Specific to configuration? No. This has also occurred on my AWS Linux 2022 arm64 box. Blazor browsers: Not applicable to this reproduction.
Other information
No response