Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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": "[email protected]",
    "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?

like image 449
MindSwipe Avatar asked Mar 12 '21 08:03

MindSwipe


1 Answers

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());
    });
}
like image 152
vernou Avatar answered Oct 12 '22 22:10

vernou