标签:
如果一个实体类里所有的时间即DateTime类型的字段,都处理成统一格式的话,可以使用如下方式:
IsoDateTimeConverter timeFormat = new IsoDateTimeConverter(); timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; JsonConvert.SerializeObject(stu, Newtonsoft.Json.Formatting.Indented, timeFormat);
如果需要返回的格式不一致,比如有的需要年月日,有的是年月日时分秒,则这样控制不了。可以通过定义属性来解决
1 public class student 2 { 3 public string Name { get; set; } 4 public int Age { get; set; } 5 [JsonConverter(typeof(DateFormat))] 6 public DateTime BirthDay { get; set; } 7 [JsonConverter(typeof(DateTimeFormat))] 8 public DateTime CreateTime { get; set; } 9 } 10 public class DateFormat:IsoDateTimeConverter 11 { 12 public DateFormat() 13 { 14 base.DateTimeFormat = "yyyy-MM-dd"; 15 } 16 } 17 public class DateTimeFormat:IsoDateTimeConverter 18 { 19 public DateTimeFormat() 20 { 21 base.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; 22 } 23 24 }
实例演示:
1 student stu = new student() 2 { 3 Name = "张三", 4 Age = 30, 5 BirthDay = new DateTime(1986, 7, 16), 6 CreateTime = DateTime.Now 7 }; 8 string result = JsonConvert.SerializeObject(stu);
result = {"Name":"张三","Age":30,"BirthDay":"1986-07-16","CreateTime":"2016-01-16 23:13:34"}
这样控制的粒度更细了
标签:
原文地址:http://www.cnblogs.com/zhouxiuquan/p/5136578.html