Home >Backend Development >C++ >How to Use Custom Enum Value Names with System.Text.Json?

How to Use Custom Enum Value Names with System.Text.Json?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-14 07:54:45930browse

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:

  1. Define a custom converter:
<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>
  1. Register the converter using JsonSerializerOptions:
<code class="language-csharp">var options = new JsonSerializerOptions
{
    Converters = { new CustomEnumStringEnumConverter() }
};</code>
  1. Apply the EnumMember attribute:

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>
  1. Serialization and deserialization:

You can now serialize and deserialize enums using custom JsonConverters:

<code class="language-csharp">// 序列化枚举值
var json = JsonSerializer.Serialize(value, options);

// 反序列化枚举值
var value = JsonSerializer.Deserialize<Enum>(json, options);</code>

Instructions:

  • This method requires .NET Core 3.1 or higher.
  • If you need to use a custom converter for multiple enumeration types, you can create a generic converter.
  • This method allows you to specify a custom name for the enumeration value while maintaining the ability to round-trip the enumeration value during serialization and deserialization.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn