Newtonsoft.Json 自定义序列化

2019-01-09  本文已影响0人  事在人为s

时间 2018-10-10 09:00

    public class ChinaDateTimeConverter : DateTimeConverterBase
    {
        private static IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm" };

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return dtConverter.ReadJson(reader, objectType, existingValue, serializer);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            dtConverter.WriteJson(writer, value, serializer);
        }
    }
    public class WorkTaskNoticeReadsModel
    {

        public string UserName { get; set; }

        public string FullName { get; set; }

        public string DeptName { get; set; }

        [JsonConverter(typeof(ChinaDateTimeConverter))]
        public DateTime ReadTime { get; set; }
    }
 
    /// <summary>  
    /// javascript时间戳毫秒  Newtonsoft.Json序列化扩展特性
    /// </summary>  
    public class TimestampConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return ConvertIntDateTime(long.Parse(reader.Value.ToString()));
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(ConvertDateTimeInt((DateTime)value));
        }

        public DateTime ConvertIntDateTime(long aSeconds)
        {
            return new DateTime(1970, 1, 1).AddMilliseconds(aSeconds);
        }

        public long ConvertDateTimeInt(DateTime aDT)
        {
            return (long)(aDT - new DateTime(1970, 1, 1)).TotalMilliseconds;
        }
    }

   public class Person
    {
        [JsonProperty("name"), JsonConverter(typeof(EmptyStringConverter))]
        public string Name { get; set; }

        [JsonProperty("date1"), JsonConverter(typeof(TimestampConverter))]
        public DateTime Date1 { get; set; }

        [JsonProperty("date2"), JsonConverter(typeof(TimestampConverter))]
        public DateTime Date2 { get; set; }

        [JsonProperty("money"), JsonConverter(typeof(MoneyConverter))]
        public decimal Money { get; set; }
    }
    
上一篇下一篇

猜你喜欢

热点阅读