JSON.NET PCL - MongoDB date json deserialization

前端之家收集整理的这篇文章主要介绍了JSON.NET PCL - MongoDB date json deserialization前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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,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; }

原文链接:https://www.f2er.com/json/290029.html

猜你在找的Json相关文章