Replies: 1 comment
|
Short answer: there is no built-in model-side attribute for this in .NET 10.
Your first method is valid C#, but on .NET 10 it hits a known System.Text.Json source-generator bug: dotnet/runtime#99669. When This was fixed by dotnet/runtime#123417, merged into
[JsonSerializable(typeof(UserDto))]
[JsonSerializable(typeof(ProductDto))]
[JsonSerializable(typeof(OrderDto))]
internal partial class MyJsonSerializerContext : JsonSerializerContext;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
[JsonSerializable(typeof(UserDto))]
internal partial class UserJsonContext : JsonSerializerContext;
[JsonSerializable(typeof(ProductDto))]
internal partial class ProductJsonContext : JsonSerializerContext;
[JsonSerializable(typeof(OrderDto))]
internal partial class OrderJsonContext : JsonSerializerContext;
var options = new JsonSerializerOptions
{
TypeInfoResolver = JsonTypeInfoResolver.Combine(
UserJsonContext.Default,
ProductJsonContext.Default,
OrderJsonContext.Default)
};Once using a System.Text.Json version that contains #123417, the distributed partial-context pattern should work: // UserDto.cs
[JsonSerializable(typeof(UserDto))]
internal partial class MyJsonSerializerContext : JsonSerializerContext;
// ProductDto.cs
[JsonSerializable(typeof(ProductDto))]
internal partial class MyJsonSerializerContext;For .NET 10, though, there is no built-in DTO annotation that automatically registers the model in a chosen context. Implementing that behavior would require a custom source generator that produces either the central context declaration or the resolver registration. |
Uh oh!
There was an error while loading. Please reload this page.
Hi, I am using .NET (AOT) with the
System.Text.Jsonsource generator.Right now, to enable static reflection (source-generated serialization), I have to manually list every DTO/model type inside a custom
JsonSerializerContext, for example:This becomes hard to maintain as the number of models grows, because I have to write all DTO/model at the same place while all DTO/model distributed in various files.
Is there a way to annotate each model class directly so that the generator automatically adds it to my
MyJsonSerializerContext? For example something like:And then the source generator would automatically include it in the specified context.
The ways I thought of
Method 1
Declare partial class
MyJsonSerializerContextat in various files:However, it does not work, I got some compiler errors:
Method 2
One class corresponds to one JsonSerializerContext.
However, I still have to regester all JsonSerializerContexts, the situation has not changed substantially.
What I am looking for
JsonIncludeInContextmentioned aboveOR
JsonSerializerContextin the distributed file with the sameJsonSerializerContextOR
Environment
Thanks!
All reactions