I have a class that contains an enum
property.
my enum:
public enum ToasterType
{
[EnumMember(Value = "success")]
success,
[EnumMember(Value = "error")]
error
}
my class :
[Serializable]
public class ToastrMessage
{
[JsonConverter(typeof(StringEnumConverter))]
public ToasterType ToasterType { get; set; }
// bla bla bla
}
return class with Json :
public async Task<ActionResult> Authentication()
{
return Json(this.ToastrMessage(ToasterType.success));
}
and output :
why 1
?
but i need something like below :
ToasterType: success
if you want to use the StringEnumConverter
for current action only then you can add following before calling json()
//convert Enums to Strings (instead of Integer)
JsonConvert.DefaultSettings = (() =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
return settings;
});
To apply the behavior globally simply add below settings in Global.asax or startup class.
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add
(new Newtonsoft.Json.Converters.StringEnumConverter());
Using Json.NET you can achieve what you need. You can create a derived class of JsonResult that uses Json.NET instead of the default ASP.NET MVC JavascriptSerializer:
/// <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());
}
}
}
Then, use this class in your Controller for return data:
public JsonResult Index()
{
var response = new ToastrMessage { ToasterType = ToasterType.success };
return new JsonNetResult { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
In this way, you get your desired result:
{ ToasterType: "success" }
Please note that this solution is based on this post, so the credits are for the author :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With