【问题标题】:return enum as string in asp.mvc and json在 asp.mvc 和 json 中将枚举作为字符串返回
【发布时间】:2015-11-21 01:02:18
【问题描述】:

我有一个包含enum 属性的类。

我的枚举:

 public enum ToasterType
    {
        [EnumMember(Value = "success")]
        success,
        [EnumMember(Value = "error")]
        error
    }

我的班级:

[Serializable]
    public class ToastrMessage
    {
        [JsonConverter(typeof(StringEnumConverter))]
        public ToasterType ToasterType { get; set; }
         // bla bla bla
    }

用 Json 返回类:

 public async Task<ActionResult> Authentication()
    {
         return Json(this.ToastrMessage(ToasterType.success));
    }

和输出:

为什么是1

但我需要类似下面的东西:

ToasterType: success

【问题讨论】:

  • 您将 Json.NET 与 JavaScriptSerializer 混为一谈。 JsonConverter 来自 Json.NET,仅当您使用 Json.NET 序列化程序时才相关。例如,请参阅this

标签: c# asp.net json enums


【解决方案1】:

如果您只想将StringEnumConverter 用于当前操作,那么您可以在调用json() 之前添加关注

//convert Enums to Strings (instead of Integer)
JsonConvert.DefaultSettings = (() =>
{
    var settings = new JsonSerializerSettings();
    settings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
    return settings;
});

要全局应用该行为,只需在 Global.asax 或启动类中添加以下设置。

HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add
            (new Newtonsoft.Json.Converters.StringEnumConverter());

【讨论】:

    【解决方案2】:

    使用 Json.NET,您可以实现您所需要的。您可以创建使用 Json.NET 而不是默认的 ASP.NET MVC JavascriptSerializer 的 JsonResult 派生类:

    /// <summary>
    /// Custom JSON result class using JSON.NET.
    /// </summary>
    public class JsonNetResult : JsonResult
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonNetResult" /> class.
        /// </summary>
        public JsonNetResult()
        {
            Settings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Error
            };
        }
    
        /// <summary>
        /// Gets the settings for the serializer.
        /// </summary>
        public JsonSerializerSettings Settings { get; set; }
    
        /// <summary>
        /// Try to retrieve JSON from the context.
        /// </summary>
        /// <param name="context">Basic context of the controller doing the request</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
    
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("JSON GET is not allowed");
            }
    
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;
    
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
    
            if (Data == null)
            {
                return;
            }
    
            var scriptSerializer = JsonSerializer.Create(Settings);
    
            using (var sw = new StringWriter())
            {
                scriptSerializer.Serialize(sw, Data);
                response.Write(sw.ToString());
            }
        }
    }
    

    然后,在你的 Controller 中使用这个类来返回数据:

    public JsonResult Index()
    {
        var response = new ToastrMessage { ToasterType = ToasterType.success };
    
        return new JsonNetResult { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
    

    这样,你就得到了你想要的结果:

    { ToasterType: "success" }
    

    请注意,这个解决方案是基于这个post,所以学分是作者的:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-17
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多