Home > Backend Development > C++ > How to Customize Enum Value Names in System.Text.Json?

How to Customize Enum Value Names in System.Text.Json?

Patricia Arquette
Release: 2025-01-14 06:55:44
Original
313 people have browsed it

How to Customize Enum Value Names in System.Text.Json?

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 &amp;&amp; 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);
    }
}
Copy after login

Additional Notes:

  • In .NET 6 and earlier, JsonStringEnumConverter ignores its naming policy during deserialization. This was fixed in .NET 7.
  • In .NET Core 3.x, the custom converter may not work as desired with [Flags] enums where individual values are renamed.
  • In .NET 5, this issue is fixed.
  • For .NET 6 or earlier, a generic converter converter factory approach may be necessary.
  • Third-party libraries like Macross.Json.Extensions simplify the process.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template