Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
System.Text.Json: How do I specify a custom name for an enum value?

Using the System.Text.Json serializer capabilities in .NET Core, how can I specify a custom value for an enum value, similar to JsonPropertyName? For example:

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
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

In .net-core-5.0 and asp.net-core-5.0, Microsoft has added support for de/serializing enums via the JsonStringEnumConverter Class.

Decorate your enumeration's values like this:

using System.Runtime.Serialization;
public enum VipStatus
{
    [EnumMember(Value = @"IS_VIP")]
    VIP = 1,

    [EnumMember(Value = @"IS_NOT_VIP")]
    NonVIP = 2,
}

Given a class like this one:

class MyClass {
    public VipStatus MyVipStatus { get; set; }
}

You could use JsonStringEnumConverter inline to serialize an instance of the class like this:

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"}

If you're using ASP.NET Core 5 then you could configure the app at startup to use JsonStringEnumConverter to serialize all incoming requests:

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());
        }
    // ...
});

More reading: How to serialize and deserialize (marshal and unmarshal) JSON in .NET Core. If you're working in ASP.NET then this is also of interest: Web defaults for JsonSerializerOptions.

over 4 years ago · Santiago Trujillo Relatório

0

In case of .NET 5:

services.AddControllers()
    .AddJsonOptions(opts => opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda