Home >Backend Development >C++ >How to Use Custom Enum Value Names with System.Text.Json?
Use custom enum value name in System.Text.Json
You can use the JsonConverter
class to specify custom names for enumeration values. Here’s how:
<code class="language-csharp">public class CustomEnumStringEnumConverter : JsonConverter<Enum> { protected override Enum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // 从JSON文本解析枚举名称 var name = reader.GetString(); // 获取枚举类型 var enumType = typeToConvert; // 按名称查找枚举值 Enum value; if (!Enum.TryParse(enumType, name, true, out value)) { throw new JsonException("无效的枚举值: " + name); } return value; } protected override void Write(Utf8JsonWriter writer, Enum value, JsonSerializerOptions options) { // 获取枚举值的自定义名称 var customName = GetCustomName(value); // 将自定义名称写入JSON文本 writer.WriteStringValue(customName); } private string GetCustomName(Enum value) { // 获取枚举值的字段信息 var fieldInfo = enumType.GetField(value.ToString()); // 获取应用于该字段的自定义属性 var attribute = fieldInfo.GetCustomAttribute<EnumMemberAttribute>(); // 返回属性中的自定义名称,如果未指定则返回默认名称 return attribute?.Value ?? value.ToString(); } }</code>
<code class="language-csharp">var options = new JsonSerializerOptions { Converters = { new CustomEnumStringEnumConverter() } };</code>
Use the EnumMember
attribute to decorate the enumeration value to specify a custom name:
<code class="language-csharp">public enum Example { [EnumMember(Value = "Trick-Or-Treat")] TrickOrTreat, // 其他枚举值 }</code>
You can now serialize and deserialize enums using custom JsonConverter
s:
<code class="language-csharp">// 序列化枚举值 var json = JsonSerializer.Serialize(value, options); // 反序列化枚举值 var value = JsonSerializer.Deserialize<Enum>(json, options);</code>
Instructions:
The above is the detailed content of How to Use Custom Enum Value Names with System.Text.Json?. For more information, please follow other related articles on the PHP Chinese website!