JsonStringEnumConverter<TEnum>
Converter to convert enums to and from strings.
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization.Converters;
namespace System.Text.Json.Serialization
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public class JsonStringEnumConverter<[System.Runtime.CompilerServices.Nullable(0)] TEnum> : JsonConverterFactory where TEnum : struct, Enum
{
private readonly JsonNamingPolicy _namingPolicy;
private readonly EnumConverterOptions _converterOptions;
public JsonStringEnumConverter()
: this((JsonNamingPolicy)null, true)
{
}
[System.Runtime.CompilerServices.NullableContext(2)]
public JsonStringEnumConverter(JsonNamingPolicy namingPolicy = null, bool allowIntegerValues = true)
{
_namingPolicy = namingPolicy;
_converterOptions = ((!allowIntegerValues) ? EnumConverterOptions.AllowStrings : (EnumConverterOptions.AllowStrings | EnumConverterOptions.AllowNumbers));
}
public sealed override bool CanConvert(Type typeToConvert)
{
return typeToConvert == typeof(TEnum);
}
[return: System.Runtime.CompilerServices.Nullable(2)]
public sealed override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
if (typeToConvert != typeof(TEnum))
ThrowHelper.ThrowArgumentOutOfRangeException_JsonConverterFactory_TypeNotSupported(typeToConvert);
return new EnumConverter<TEnum>(_converterOptions, _namingPolicy, options);
}
}
}