Skip to content

Instantly share code, notes, and snippets.

@pagebrooks
Created December 7, 2012 00:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pagebrooks/4229693 to your computer and use it in GitHub Desktop.
Save pagebrooks/4229693 to your computer and use it in GitHub Desktop.
Angular Compatible Date Formatting with JSON.NET
public class JsonNetResult : JsonResult
{
private readonly static JsonSerializerSettings Settings;
private readonly static IsoDateTimeConverter _dateTimeConverter;
static JsonNetResult()
{
_dateTimeConverter = new IsoDateTimeConverter();
// Default for IsoDateTimeConverter is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK
_dateTimeConverter.DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFK";
Settings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter> { _dateTimeConverter }
};
}
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
var json = JsonConvert.SerializeObject(Data, Settings);
response.Write(json);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment