Usando las capacidades del serializador System.Text.Json en .NET Core, ¿cómo puedo especificar un valor personalizado para un valor de enumeración, similar a JsonPropertyName ? Por ejemplo:
public enum Example { Trick, Treat, [JsonPropertyName("Trick-Or-Treat")] // Error: Attribute 'JsonPropertyName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. TrickOrTreat }En .net-core-5.0 y asp.net-core-5.0 , Microsoft ha agregado soporte para deserializar enumeraciones a través de JsonStringEnumConverter Class .
Decora los valores de tu enumeración así:
using System.Runtime.Serialization; public enum VipStatus { [EnumMember(Value = @"IS_VIP")] VIP = 1, [EnumMember(Value = @"IS_NOT_VIP")] NonVIP = 2, }Dada una clase como esta:
class MyClass { public VipStatus MyVipStatus { get; set; } }Podría usar JsonStringEnumConverter en línea para serializar una instancia de la clase como esta:
using System.Text.Json; using System.Text.Json.Serialization; // ... var myObjectWithEnums = new MyClass() { MyVipStatus = VipStatus.NonVIP }; var options = new JsonSerializerOptions(); // Configures serialization to allow strings to be accepted and auto-converted to enum values. options.Converters.Add(new JsonStringEnumConverter()); var json = JsonSerializer.Serialize(myObjectWithEnums, options); // serialized output is: { "myVipStatus": "IS_NOT_VIP"}Si usa ASP.NET Core 5, puede configurar la aplicación al inicio para usar JsonStringEnumConverter para serializar todas las solicitudes entrantes:
public async void ConfigureServices(IServiceCollection services) { // ... services .AddControllers() .AddJsonOptions(options => { // Configures serialization to allow strings to be accepted and auto-converted to enum values. options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); } // ... });Más lecturas: Cómo serializar y deserializar (marshal y unmarshal) JSON en .NET Core . Si está trabajando en ASP.NET, esto también es de su interés: Valores predeterminados web para JsonSerializerOptions .
En el caso de .NET 5:
services.AddControllers() .AddJsonOptions(opts => opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));