Newtonsoft.Json自定義序列化

 

 

 1     public class ChinaDateTimeConverter : DateTimeConverterBase  2  {  3         private static IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm" };  4 
 5         public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)  6  {  7             return dtConverter.ReadJson(reader, objectType, existingValue, serializer);  8  }  9 
10         public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 11  { 12  dtConverter.WriteJson(writer, value, serializer); 13  } 14  } 15     public class WorkTaskNoticeReadsModel 16  { 17 
18         public string UserName { get; set; } 19 
20         public string FullName { get; set; } 21 
22         public string DeptName { get; set; } 23 
24         [JsonConverter(typeof(ChinaDateTimeConverter))] 25         public DateTime ReadTime { get; set; } 26  } 27  
28     /// <summary>  
29     /// javascript時間戳毫秒 Newtonsoft.Json序列化擴展特性 30     /// </summary>  
31     public class TimestampConverter : JsonConverter 32  { 33         public override bool CanConvert(Type objectType) 34  { 35             return objectType == typeof(DateTime); 36  } 37 
38         public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 39  { 40             return ConvertIntDateTime(long.Parse(reader.Value.ToString())); 41  } 42 
43         public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 44  { 45  writer.WriteValue(ConvertDateTimeInt((DateTime)value)); 46  } 47 
48         public DateTime ConvertIntDateTime(long aSeconds) 49  { 50             return new DateTime(1970, 1, 1).AddMilliseconds(aSeconds); 51  } 52 
53         public long ConvertDateTimeInt(DateTime aDT) 54  { 55             return (long)(aDT - new DateTime(1970, 1, 1)).TotalMilliseconds; 56  } 57  } 58 
59    public class Person 60  { 61         [JsonProperty("name"), JsonConverter(typeof(EmptyStringConverter))] 62         public string Name { get; set; } 63 
64         [JsonProperty("date1"), JsonConverter(typeof(TimestampConverter))] 65         public DateTime Date1 { get; set; } 66 
67         [JsonProperty("date2"), JsonConverter(typeof(TimestampConverter))] 68         public DateTime Date2 { get; set; } 69 
70         [JsonProperty("money"), JsonConverter(typeof(MoneyConverter))] 71         public decimal Money { get; set; } 72     }
相關文章
相關標籤/搜索