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