System.Text.Json: Custom Enum Value Names
System.Text.Json does not provide a built-in way to specify custom values for enum members. However, there are several options for achieving this:
Using a Custom JsonConverterFactory:
Create a custom converter class that inherits from JsonConverterFactory and implements the CanConvert and CreateConverter methods. In CanConvert, check if the type to be converted is an enum. In CreateConverter, create a customized JsonEnumConverter instance that handles the custom values.
Using a Third-Party Library:
Libraries like Macross.Json.Extensions provide converters that support custom enum value names. Install the library and decorate your enum with [JsonConverter(typeof(JsonStringEnumMemberConverter))].
Creating a Custom Converter and Factory in .NET 6 or Earlier:
In .NET 6 or earlier, a custom converter and converter factory are needed for round-tripping enums with custom names. This involves handling parsing of integer and string values, renaming of [Flags] enum components, and converting enums of all possible underlying types.
Using a Generic Enum Converter:
A generic enum converter can be created to handle both [Flags] and non-[Flags] enums, with custom override for name conversion if needed. This is more involved than using a specific converter for each type.
Code Example using a Custom Converter Factory:
public class JsonEnumMemberStringEnumConverter : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) => baseConverter.CanConvert(typeToConvert); public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var query = from field in typeToConvert.GetFields(BindingFlags.Public | BindingFlags.Static) let attr = field.GetCustomAttribute<EnumMemberAttribute>() where attr != null && attr.Value != null select (field.Name, attr.Value); var dictionary = query.ToDictionary(p => p.Item1, p => p.Item2); if (dictionary.Count > 0) return new JsonStringEnumConverter(new DictionaryLookupNamingPolicy(dictionary, namingPolicy), allowIntegerValues).CreateConverter(typeToConvert, options); else return baseConverter.CreateConverter(typeToConvert, options); } }
Additional Notes:
The above is the detailed content of How to Customize Enum Value Names in System.Text.Json?. For more information, please follow other related articles on the PHP Chinese website!