Open ithline opened 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: | ithline |
---|---|
Assignees: | - |
Labels: | `api-suggestion`, `area-System.Text.Json` |
Milestone: | - |
Sounds reasonable.
The Converters property accepts Type[]? array, so it cannot be used either.
You can always try extending the converter class with a custom naming policy and specify that in the Converters
property:
public enum MyEnum { A, B, C };
[JsonSourceGenerationOptions(Converters = new[] { typeof(CamelCaseJsonStringEnumConverter<MyEnum>)})]
[JsonSerializable(typeof(MyEnum))]
public partial class MyContext : JsonSerializerContext { }
public class CamelCaseJsonStringEnumConverter<TEnum>()
: JsonStringEnumConverter<TEnum>(JsonNamingPolicy.CamelCase) where TEnum : struct, Enum;
This would solve a lot of issues with the fact that the JsonStringEnumConverter locks you into CamelCase, and some of us need snake or kebob case instead for certain enumerations.
The Converters property accepts Type[]? array, so it cannot be used either.
You can always try extending the converter class with a custom naming policy and specify that in the
Converters
property:public enum MyEnum { A, B, C }; [JsonSourceGenerationOptions(Converters = new[] { typeof(CamelCaseJsonStringEnumConverter<MyEnum>)})] [JsonSerializable(typeof(MyEnum))] public partial class MyContext : JsonSerializerContext { } public class CamelCaseJsonStringEnumConverter<TEnum>() : JsonStringEnumConverter<TEnum>(JsonNamingPolicy.CamelCase) where TEnum : struct, Enum;
Or you can make a factory to support all enums.
internal sealed class JsonStringEnumCamelCaseConverter : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert.IsEnum;
}
public override JsonConverter? CreateConverter(
Type typeToConvert,
JsonSerializerOptions options
)
{
if (!typeToConvert.IsEnum)
throw new ArgumentException("Type should be enum.", nameof(typeToConvert));
var constructedType = typeof(JsonStringEnumConverter<>).MakeGenericType(typeToConvert);
return (JsonConverter)
Activator.CreateInstance(
constructedType,
BindingFlags.Default,
null,
[JsonNamingPolicy.CamelCase, true],
null
)!;
}
}
Background and motivation
Recently there has been added
UseStringEnumConverter
flag toJsonSourceGenerationOptions
, but there is no way to configure naming policy for these converters.The
Converters
property acceptsType[]?
array, so it cannot be used either.API Proposal
API Usage
Alternative Designs
No response
Risks
No response