Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return enum as string in asp.mvc and json

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 :

enter image description here

why 1 ?

but i need something like below :

ToasterType: success
like image 273
testStack Avatar asked Aug 26 '15 20:08

testStack


2 Answers

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());
like image 99
vendettamit Avatar answered Oct 11 '22 14:10

vendettamit


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 :)

like image 30
Hernan Guzman Avatar answered Oct 11 '22 15:10

Hernan Guzman