6

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
testStack
  • 345
  • 1
  • 6
  • 18
  • 2
    You are mixing up Json.NET with the `JavaScriptSerializer`. `JsonConverter` is from Json.NET and is only relevant if you are using the Json.NET serializer. See, for example, [this](http://stackoverflow.com/questions/23348262/using-json-net-to-return-actionresult) – Matt Burland Aug 26 '15 at 20:23

2 Answers2

4

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());
vendettamit
  • 14,315
  • 2
  • 32
  • 54
2

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

Hernan Guzman
  • 1,235
  • 8
  • 14