简体   繁体   English

将 JSON 字符串 integer 反序列化为 ASP.NET 内核中的枚举

[英]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我正在创建一个 ASP.NET 核心 API 并且我的用户有一个角色,就像这样

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现在的问题是,我的用户CreateOrUpdate端点正在获取此 JSON 数据

{
    "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 .它无法反序列化,因此返回HTTP 400 Bad Request But, if I remove the quotation marks around the 0 of the role property, it works like a charm.但是,如果我删除role属性0周围的引号,它就像一个魅力。

So, how do I get ASP.NET Core to deserialize the "0" to a 0 and as such to the enum variant User ?那么,如何让 ASP.NET 核心将"0"反序列化为0以及枚举变体User

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.视情况而定,如果您使用NewtonsoftMicrosoft.Json.Text ,则实现或多或少相同,但您必须注意使用正确命名空间之外的类和属性,并且不要混合使用它们。

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.根据您的使用情况,您可以查看MicrosoftNewtonsoftStringEnumConverter的原始代码,并在此基础上编写自己的代码。

In your class you can then apply this converter by using the corresponding attribute to the specific attribute.然后,在您的 class 中,您可以通过将相应属性应用于特定属性来应用此转换器。

From How to customize property names and values with System.Text.Json - Enum as string .如何使用 System.Text.Json-Enum as string 自定义属性名称和值

By default, System.Text.Json convert enum from integer, but in you case "0" is a string.默认情况下,System.Text.Json 从 integer 转换枚举,但在你的情况下,“0”是一个字符串。 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());
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM