Skip to content

Instantly share code, notes, and snippets.

@remelpugh
Forked from DavidDeSloovere/JsonNetResult
Last active August 29, 2015 14:25
Show Gist options
  • Save remelpugh/1ba0b5ef48a412c5a692 to your computer and use it in GitHub Desktop.
Save remelpugh/1ba0b5ef48a412c5a692 to your computer and use it in GitHub Desktop.
JsonNetResult for ASP.NET MVC - correct formatting of dates and camel cased properties Got most of the code from Stack Overflow.
using System;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class JsonNetResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/json";
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data == null)
{
return;
}
var jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var formatting = HttpContext.Current != null && HttpContext.Current.IsDebuggingEnabled ? Formatting.Indented : Formatting.None;
var serializedObject = JsonConvert.SerializeObject(Data, formatting, jsonSerializerSettings);
response.Write(serializedObject);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment