Use a customized JsonConverter to handle deserilizatrion the MongoDb based datetime json
"Submitted" : { "$date" : 1413030537700 }
the converter:
public class MongoDateConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(DateTime));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jObj = JObject.Load(reader);
string dateText = jObj["$date"].ToString();
long timeLong = long.Parse(dateText);
DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0,DateTimeKind.Utc);
return unixEpoch.AddMilliseconds(timeLong);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value.ToString());
}
}
Apply the converter on data model fields like below:
[JsonConverter(typeof(MongoDateConverter))] public DateTime Submitted { get; set; }