Well this has probably been done 100 times before but so what, the world could always use more code. When working with ASP.Net MVC I started and fell in love with James Newton-King’s Json.Net library. It is simple awesome and does an amazing job in different parts of my app. The control over the serialzation and deserialization is very good and thought it would be well suited for my MVC application.
You might be thinking, why not just use the one that comes with .Net. It’s in the box and is just as good. Well my preference was control, I wanted to control my model better and I wanted to output Json differently in different situations. So I created a new ActionResult that does just that but with the Json.Net library. Enjoy!
Example usage in any controller action:
public ActionResult List(int Year, int Month) { if (Year == 0) Year = DateTime.Now.Year; if (Month == 0) Month = DateTime.Now.Month; var calendarMonth = _calendarService.GetCalendarMonth(Year, Month, !this.IsAdmin()); return new JsonNetResult(calendarMonth); }
The code is below, but it can also be downloaded here and found on Github here.
using System; using System.Text; using System.Web.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace com.bytecyclist { 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(); SerializerSettings.Converters.Add(new JavaScriptDateTimeConverter()); Formatting = Formatting.None; } public JsonNetResult(object data) : this() { Data = data; } public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); var response = context.HttpContext.Response; response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; if (Data == null) return; var writer = new JsonTextWriter(response.Output) { Formatting = Formatting }; var serializer = JsonSerializer.Create(SerializerSettings); serializer.Serialize(writer, Data); writer.Flush(); } } }