[英]return enum as string in asp.mvc and json
我有一個包含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
如果你只想使用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());
使用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" }
請注意,這個解決方案是基於這篇文章 ,所以學分是為作者:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.