0

I'm learning the new JSON library that is integrated in Dotnet Core 5.0. Now I have problems with customizing the enum values to specific strings. I saw some tutorials over the Internet that stated that the attribute EnumMember can be used for specifying the serialized value of the appropriate enum value. But this is not working for me. I published the code on dotnetfiddle, so you are welcome to test the code.

using System;
using System.Runtime.Serialization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
                
public enum Animals 
{
    [EnumMember(Value = "dog2")]
    Dog, 
    [EnumMember(Value = "cat")]
    Cat, 
    [EnumMember(Value = "black_bear")]
    BlackBear 
}

public class Program
{
    public static void Main()
    {
        var options = new JsonSerializerOptions();
        options.Converters.Add(new JsonStringEnumConverter());
        string tmp = JsonSerializer.Serialize(Animals.Dog,options);
        Console.WriteLine(tmp);
    }
}
dbc
  • 91,441
  • 18
  • 186
  • 284
user12682244
  • 1
  • 1
  • 2
  • `EnumMember` isn't used by System.Text.Json. You'll have to create a custom converter like the one shown in the duplicate. The tutorials you show weren't for .NET Core's System.Text.Json. Why do you want to use a different name in the first place though? `cat` doesn't need to be capitalized. Why not use `Dog2` and `Black_Bear` to match the actual JSON text. – Panagiotis Kanavos May 16 '22 at 07:20

0 Answers0