-
Notifications
You must be signed in to change notification settings - Fork 4.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[API Proposal]: Add option to specify JsonNamingPolicy for enum serialization on JsonSourceGenerationOptions #92828
Comments
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis Issue DetailsBackground and motivationRecently there has been added The API Proposalnamespace System.Text.Json.Serialization;
public partial class JsonSourceGenerationOptionsAttribute : JsonAttribute
{
public JsonKnownNamingPolicy EnumNamingPolicy { get; set; }
} API Usage[JsonSourceGenerationOptions(
UseStringEnumConverter = true,
EnumNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
internal sealed partial class MyJsonContext : JsonSerializerContext
{
} Alternative DesignsNo response RisksNo response
|
Sounds reasonable. |
You can always try extending the converter class with a custom naming policy and specify that in the 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. |
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
The text was updated successfully, but these errors were encountered: