Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

533
Vistas
Deserialize a JSON string integer to an Enum in ASP.NET Core

I'm creating an ASP.NET Core API and my users have a role, like so

class User
{
    public Guid Id {get; set;}

    public string Email {get; set;}

    public Role Role {get; set;}
}

enum Role : byte
{
    User = 0,
    Administrator = 1
}

The problem now is, that my user CreateOrUpdate endpoint is getting this JSON data

{
    "id": "2abe50d6-4c81-4ace-ad95-c8182d4384a3",
    "email": "someEmail@example.org",
    "role": "0"
}

Here's the problematic endpoint declaration

public User CreateOrUpdate([FromBody] User user)
{
    // ...
}

And it fails to deserialize this, and as such returns HTTP 400 Bad Request. But, if I remove the quotation marks around the 0 of the role property, it works like a charm.

So, how do I get ASP.NET Core to deserialize the "0" to a 0 and as such to the enum variant User?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

From How to customize property names and values with System.Text.Json - Enum as string.

By default, System.Text.Json convert enum from integer, but in you case "0" is a string. You need specify a converter to convert enum from string like :

public void ConfigureServices(IServiceCollection services)
{

    services.AddControllers().AddJsonOptions(o =>
    {
        o.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
    });
}
over 4 years ago · Santiago Trujillo Denunciar

0

You have to write your own converter. Depending, if you're using either Newtonsoft or Microsoft.Json.Text the implementation are more or less the same, but you have to take care to use the classes and properties out of the right namespace and do not mix them.

Depending on your usage you can take a look into the original code of the StringEnumConverter either at Microsoft or Newtonsoft and write your own based on that.

In your class you can then apply this converter by using the corresponding attribute to the specific attribute.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda