I have switched some of my jsonresult controller methods to use json.net for serialization. Why? Because I needed enums to be serialized by their names instead of their values.
To do this, do the following:
- Add json.net to your project. You can do this through nuget or manually.
- Create the following class (from http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx):
public class JsonNetResult : ActionResult
{
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult()
{
SerializerSettings = new JsonSerializerSettings();
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
{
JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
}
- Change your controller method signature from the following:
public JsonResult GetItems(inputClass input)
to the following:
public ActionResult GetItems(inputClass input)
- Change your return statement from:
return Json(model);
to
return new JSONMvc.JsonNetResult() { Data = model };
- Put an attribute on your property that will cause it to be serialized by name:
[JsonConverter(typeof(StringEnumConverter))]
public enuFilterType FilterType
That’s it. Now, YMMV. I did this, and everything worked 100% with no other changes on server or client. However, because it was so easy, I haven’t dug into the code to see if there are any hidden issues I might run into later, like slightly different serialization for dates, for example. But as of now, my problem with enum serialization is solved.