如何告诉JSON.. NET StringEnumConverter接受DisplayName

本文关键字:接受 DisplayName StringEnumConverter NET 何告诉 JSON | 更新日期: 2023-09-27 18:15:08

我有以下模型:

public enum Status
{
    [Display(Name = "Awaiting Approval")]
    AwaitingApproval,
    Rejected,
    Accepted,
}

我在一个模型中使用这个enum:

public class Docs
    {
        [Key]
        public int Id { get; set; }
        [JsonConverter(typeof(StringEnumConverter))]
        public Status Status { get; set; }
    }

现在可以正常工作了;序列化器返回与枚举等价的字符串。我的问题是如何告诉JSON。

如何告诉JSON.. NET StringEnumConverter接受DisplayName

使用Display属性而不是string ?

您应该尝试使用[EnumMember]而不是[Display]。您也可以将[JsonConverter]属性放在枚举本身上。

[JsonConverter(typeof(StringEnumConverter))]
public enum Status
{
    [EnumMember(Value = "Awaiting Approval")]
    AwaitingApproval,
    Rejected,
    Accepted,
}

VB。. NET版本的JsonConverter属性为:

<Newtonsoft.Json.JsonConverter(GetType(Newtonsoft.Json.Converters.StringEnumConverter))>

在WebAPI中,最好的选择是全局转换JSON中的所有枚举字符串与描述值

  1. 在Model中使用此命名空间using Newtonsoft.Json.Converters;

    public class Docs
    {
    [Key]
    public int Id { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    public Status Status { get; set; }
    }
    
  2. 在Enum中使用此命名空间using System.Runtime.Serialization;对于EnumMember

    public enum Status
    {
    [EnumMember(Value = "Awaiting Approval")]
    AwaitingApproval,
    Rejected,
    Accepted,
    }
    
  3. 在全球。请添加此代码

        protected void Application_Start()
        {
          GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
        }
    

我尝试了这个,得到了错误type or namespace enum member could not be found...你们可能也会遇到这个错误所以你们需要使用

using System.Runtime.Serialization;

,你仍然得到这个错误,然后添加一个引用,像这样:

Right click on your project -> Add -> Reference.. -> Assemblies -> Mark System.Runtime.Serialization (i have 4.0.0.0 version ) -> Ok

现在你可以像这样继续:

[JsonConverter(typeof(StringEnumConverter))]
public enum Status
{
    [EnumMember(Value = "Awaiting Approval")]
    AwaitingApproval,
    Rejected,
    Accepted,
}