Home Backend Development C++ How to Specify Custom Names for Enum Values in System.Text.Json?

How to Specify Custom Names for Enum Values in System.Text.Json?

Jan 14, 2025 am 10:37 AM

How to Specify Custom Names for Enum Values in System.Text.Json?

System.Text.Json: How do I specify a custom name for an enum value?

This capability is not available out of the box in .NET Core 3.0, .NET 5, .NET 6.0, .NET 7.0, or .NET 8.0. Therefore, you will need to create your own JsonConverterFactory that serializes enums with custom value names specified by attributes, or use a NuGet package that does the same, such as Macross.Json.Extensions.

If you are working in .NET 7 or later, or only need to serialize but not deserialize enums with custom names in earlier versions, custom names can be easily supported by creating a JsonConverterFactory that adapts JsonStringEnumConverter by constructing a customized JsonNamingPolicy for each enum with [EnumMember(Value = "xxx")] applied to any enum value.

Here are the steps involved:

  1. Create a custom converter:
public class JsonEnumMemberStringEnumConverter : JsonConverterFactory
{
    public JsonEnumMemberStringEnumConverter() : this(null, true) { }

    public JsonEnumMemberStringEnumConverter(JsonNamingPolicy? namingPolicy = null, bool allowIntegerValues = true)
    {
        this.namingPolicy = namingPolicy;
        this.allowIntegerValues = allowIntegerValues;
        this.baseConverter = new JsonStringEnumConverter(namingPolicy, allowIntegerValues);
    }

    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);
    }
}

public class JsonNamingPolicyDecorator : JsonNamingPolicy
{
    readonly JsonNamingPolicy? underlyingNamingPolicy;

    public JsonNamingPolicyDecorator(JsonNamingPolicy? underlyingNamingPolicy) => this.underlyingNamingPolicy = underlyingNamingPolicy;
    public override string ConvertName(string name) => underlyingNamingPolicy?.ConvertName(name) ?? name;
}

internal class DictionaryLookupNamingPolicy : JsonNamingPolicyDecorator
{
    readonly Dictionary<string, string> dictionary;

    public DictionaryLookupNamingPolicy(Dictionary<string, string> dictionary, JsonNamingPolicy? underlyingNamingPolicy) : base(underlyingNamingPolicy) => this.dictionary = dictionary ?? throw new ArgumentNullException();
    public override string ConvertName(string name) => dictionary.TryGetValue(name, out var value) ? value : base.ConvertName(name);
}
  1. Decorate your enum:
public enum Example
{
    Trick,
    Treat,
    [EnumMember(Value = "Trick-Or-Treat")]
    TrickOrTreat,
}
  1. Use the converter standalone:
var options = new JsonSerializerOptions
{
    Converters = { new JsonEnumMemberStringEnumConverter() },
    // Set other options as required:
    WriteIndented = true,
};
var json = JsonSerializer.Serialize(values, options);
  1. Register the converter with ASP.NET Core:

Refer to the answer to this question by Mani Gandham for guidance on how to do this.

Notes:

  • In .NET 6 and earlier, JsonStringEnumConverter ignores its naming policy during deserialization; this issue was fixed in pull request 73348.
  • In .Net Core 3.x, the converter may not work as desired with [Flags] enums. This issue was fixed in Issue #31622 in .NET 5.
  • If you need to round-trip an enum with custom value names in .NET 6 or earlier, you will need to create a generic converter converter factory from scratch.
  • An alternative solution is to use JsonStringEnumMemberConverter from the Macross.Json.Extensions package. Install the package and then decorate your enum with the attribute [JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumMemberConverter))].

I hope this explanation helps! Let me know if you have any other questions.

The above is the detailed content of How to Specify Custom Names for Enum Values in System.Text.Json?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to compile and run a C   program How to compile and run a C program Sep 16, 2025 am 05:29 AM

InstallaC compilerlikeg usingpackagemanagersordevelopmenttoolsdependingontheOS.2.WriteaC programandsaveitwitha.cppextension.3.Compiletheprogramusingg hello.cpp-ohellotogenerateanexecutable.4.Runtheexecutablewith./helloonLinux/macOSorhello.exeonWi

How to execute a system command in C How to execute a system command in C Sep 21, 2025 am 04:35 AM

Use the std::system() function to execute system commands, which need to include header files and pass in C-style string commands, such as std::system("ls-l"), and the return value is -1, which means that the command processor is not available.

C   custom allocator example C custom allocator example Sep 17, 2025 am 08:45 AM

Custom allocator can be used to control the memory allocation behavior of C containers. 1. The LoggingAllocator in the example implements memory operation logging by overloading allocate, deallocate, construct and destroy methods; 2. The allocator needs to define value_type and rebind templates to meet the STL container type conversion requirements; 3. The allocator triggers log output during construction and copying, which is convenient for tracking the life cycle; 4. Actual applications include memory pools, shared memory, debugging tools and embedded systems; 5. Since C 17, construct and destroy can be processed by std::allocator_traits by default

How to use a stack in C How to use a stack in C Sep 21, 2025 am 05:16 AM

C's stack is a container adapter in STL. It follows the principle of back-in-first-out and must include header files; add elements by push, pop removes the top element, and top accesses the top of the stack. Before the operation, check whether it is empty, which is often used in scenarios such as expression evaluation and backtracking.

How to implement a custom iterator in C How to implement a custom iterator in C Sep 20, 2025 am 01:13 AM

The answer is to define a class that contains the necessary type alias and operations. First, set value_type, reference, pointer, difference_type and iterator_category, then implement dereference, increment and comparison operations. Finally, provide begin() and end() methods in the container to return the iterator instance, making it compatible with STL algorithms and range for loops.

C   abstract class example C abstract class example Sep 15, 2025 am 05:55 AM

An abstract class is a class containing at least one pure virtual function. It cannot be instantiated and must be inherited as a base class. The derived class needs to implement all its pure virtual functions, otherwise it will still be an abstract class. 1. Pure virtual functions are declared by virtual return type function name()=0; to define interface specifications; 2. Abstract classes are often used for unified interface design, such as area(), draw(), etc., to implement polymorphic calls; 3. Virtual destructors must be provided for abstract classes (such as virtual~Shape()=default;) to ensure that derived class objects are correctly released through base class pointers; 4. After the derived class inherits, pure virtual functions must be rewrite, such as Rectangle and Circle to implement area() to calculate their respective areas; 5.

How to use auto in modern C How to use auto in modern C Sep 24, 2025 am 04:59 AM

Theautokeywordletsthecompilerdeducevariabletypesfrominitializers,reducingverbosityandimprovingmaintainability.Itsimplifiescodewithcomplextypeslikeiteratorsandlambdas,supportsreferencesandconstqualifierstoavoidunnecessarycopies,andadaptsautomaticallyw

How to set up a C   project with CMake? How to set up a C project with CMake? Sep 18, 2025 am 01:04 AM

Create a project directory structure, including CMakeLists.txt, src/ and include/; 2. Write CMakeLists.txt, specify the CMake version, project name, C standard and add executable files; 3. Use mkdirbuild to enter the directory and run cmake.. and cmake--build. for compilation; 4. Add multiple source files through add_executable, and use target_include_directories to include the header file path; 5. Use find_package to find external libraries and link with target_link_libraries; 6.

See all articles