How to tell JSON.NET StringEnumConverter to take DisplayName?

前端 未结 3 1934
死守一世寂寞
死守一世寂寞 2021-02-02 12:31

I\'ve got the following model:

public enum Status
{
    [Display(Name = \"Awaiting Approval\")]
    AwaitingApproval,
    Rejected,
    Accepted,
}
3条回答
  •  盖世英雄少女心
    2021-02-02 13:09

    In WebAPI the best option is to globally convert all enum string in JSON with Description value

    1. In Model use this namespace using Newtonsoft.Json.Converters;

      public class Docs
      {
      [Key]
      public int Id { get; set; }
      [JsonConverter(typeof(StringEnumConverter))]
      public Status Status { get; set; }
      }
      
    2. In Enum use this namespace using System.Runtime.Serialization; for EnumMember

      public enum Status
      {
      [EnumMember(Value = "Awaiting Approval")]
      AwaitingApproval,
      Rejected,
      Accepted,
      }
      
    3. In Global.asax add this code

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

    It will work fine return enum in JSON using WebAPI.

提交回复
热议问题