C
C#3w ago
Core

✅ How is JsonConverter(typeof(JsonStringEnumConverter<MyEnum>)) evaluated?

Hello, This makes it possible that enum is serialized to string when the request comes in. Is this evaluated on each request, or only once at compile time?
c#
[JsonConverter(typeof(JsonStringEnumConverter<Precipitation>))]
public enum Precipitation
{
Drizzle, Rain, Sleet, Hail, Snow
}
c#
[JsonConverter(typeof(JsonStringEnumConverter<Precipitation>))]
public enum Precipitation
{
Drizzle, Rain, Sleet, Hail, Snow
}
4 Replies
Pobiega
Pobiega3w ago
happens at runtime, but if using source generation with STJ, it will, as the name implies, source generate the actual glue-code to call the converter
Core
CoreOP3w ago
there is one problem with that, I configured the source generation after the docs. But now the serialization only works with those classes, any other DTO, even the ones not using enums will throw an exteption. This means that for every new DTO 2 more classes must be added to the serializer, this is really inconvenient. Or I might be doing something wrong
c#
[JsonSourceGenerationOptions(UseStringEnumConverter = true)]
[JsonSerializable(typeof(ListLinksRequest))]
[JsonSerializable(typeof(ListLinksResult))]
public partial class EnumJsonSerializer : JsonSerializerContext;
c#
[JsonSourceGenerationOptions(UseStringEnumConverter = true)]
[JsonSerializable(typeof(ListLinksRequest))]
[JsonSerializable(typeof(ListLinksResult))]
public partial class EnumJsonSerializer : JsonSerializerContext;
Program.cs
c#
c.Serializer.Options.TypeInfoResolver = JsonTypeInfoResolver.Combine(EnumJsonSerializer.Default);
c#
c.Serializer.Options.TypeInfoResolver = JsonTypeInfoResolver.Combine(EnumJsonSerializer.Default);
I think this way the default serializer gets overridden, is there a way I could specify the default JsonTypeInfoResolver for the Combine() method? This seemed to work
c.Serializer.Options.TypeInfoResolver =
JsonTypeInfoResolver.Combine(c.Serializer.Options.TypeInfoResolver, EnumJsonSerializer.Default);
c.Serializer.Options.TypeInfoResolver =
JsonTypeInfoResolver.Combine(c.Serializer.Options.TypeInfoResolver, EnumJsonSerializer.Default);
Pobiega
Pobiega3w ago
could you try appending to the chain instead? options.TypeInfoResolverChain.Add(YourSerializer.Default); seems cleaner to me
Core
CoreOP3w ago
This guy serializes 😄 Thank you so much
Want results from more Discord servers?
Add your server