using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.ComponentModel;
using System.Globalization;
using System.Collections.Specialized;
using System.Web.Routing;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class CustomDateConverter : JsonConverter
private string[] formats = new string[] { "yyyy-MM-dd", "MM/dd/yy", "MM/dd/yyyy", "dd-MMM-yy" };
public CustomDateConverter(params string[] dateFormats)
this.formats = dateFormats;
Console.WriteLine(string.Format("Constructed a {0} with arguments {1}", GetType(), JsonConvert.SerializeObject(dateFormats)));
public override bool CanConvert(Type objectType)
return objectType == typeof(DateTime);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
throw new InvalidOperationException();
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
var date = (DateTime)value;
writer.WriteValue(date.ToString(formats.Last()));
[JsonConverter(typeof(CustomDateConverter), new object [] { new string [] { "dd-MMM-yy", "yyyy-MM-dd", "MM/dd/yy", "MM/dd/yyyy" } } )]
public DateTime DateTime { get; set; }
public static void Test()
var root = new RootObject { DateTime = DateTime.Now };
var json = JsonConvert.SerializeObject(root);
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);