C#C
C#14mo ago
Core

✅ .NET 8 enum to string serialization throws an exception

Hello,
Following the docs, a custom JsonSerializerContext is applied on the controllers, yet an exception is thrown.

c#
public sealed record GetLinkMetricsRequest
{
    [FromRoute]
    public string Id { get; set; }
    
    [FromQuery]
    public TimePeriodUnit? TimeUnit { get; set; } = TimePeriodUnit.Day;
    
    [FromQuery]
    public int? Units { get; set; }
}

[JsonSourceGenerationOptions(UseStringEnumConverter = true)]
[JsonSerializable(typeof(GetLinkMetricsRequest))]
public partial class TimePeriodUnitJsonContext : JsonSerializerContext;


// applied to the Controllers
var options = new JsonSerializerOptions
{
    TypeInfoResolver = JsonTypeInfoResolver.Combine(ContextA.Default, ContextB.Default, ContextC.Default);
};



The exception:

An unexpected error occurred. See the inner exception for details. System.NotSupportedException: JsonTypeInfo metadata for type 'AnalyticsService.Api..' was not provided by TypeInfoResolver of type 'System.Text.Json.Serialization.Metadata.JsonTypeInfoResolverWithAddedModifiers'. If using source generation, ensure that all root types passed to the serializer have been annotated with 'JsonSerializableAttribute', along with any types that might be serialized polymorphically.


I have followed the docs:
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation#combine-source-generators
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation#blanket-policy
Learn how to use source generation in System.Text.Json.
Was this page helpful?