<PackageReference Include="System.Text.Json" Version="5.0.0" />

JsonStringEnumConverter

Converts enumeration values to and from strings.
using System.Reflection; 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 sealed class JsonStringEnumConverter : JsonConverterFactory { private readonly JsonNamingPolicy _namingPolicy; private readonly EnumConverterOptions _converterOptions; public JsonStringEnumConverter() : this(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 override bool CanConvert(Type typeToConvert) { return typeToConvert.IsEnum; } public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { return (JsonConverter)Activator.CreateInstance(typeof(EnumConverter<>).MakeGenericType(typeToConvert), BindingFlags.Instance | BindingFlags.Public, null, new object[3] { _converterOptions, _namingPolicy, options }, null); } } }