I'm moving some libraries to .NET 8 and I'm trying to use the new JsonNamingPolicy.SnakeCaseLower for enums (I have a custom converter that I currently use that uses reflection but I want to drop it). I can serialize an enum to snake case using this JsonSerializerOptions:
JsonSerializerOptions options = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
};
options.Converters.Add(new JsonStringEnumConverter(namingPolicy: JsonNamingPolicy.SnakeCaseLower));
The problem is that according to the documentation The non-generic JsonStringEnumConverter type is not supported for AOT. The solution given is using [JsonSourceGenerationOptions(UseStringEnumConverter = true)] in the class inheriting from JsonSerializerContext but then I lose the naming policy for enums.
Is there a way to use JsonNamingPolicy.SnakeCaseLower globally for all enums in an AOT-friendly way?