Newtonsoft.Json.dll提供了非常好的Json序列化和反序列化方式,但是对日期的处理却让我纠结了很久。首先定义类如下:
public class Student{ public int Id{get;set;} public string Name{get;set;} public DateTime BirthDay{get;set;} }
序列化代码如下:
Student stu = new Student() { Id = 1, Name = "zhangsan", BirthDay = DateTime.Now }; String result = Newtonsoft.Json.JsonConvert.SerializeObject(stu); Console.WriteLine(result); Console.ReadLine();
结果是:{"Id":1,"Name":"zhangsan","BirthDay":"2016-08-03T17:23:54.2480422+08:00"}
修改代码如下:
Student stu = new Student() { Id = 1, Name = "zhangsan", BirthDay = DateTime.Now }; Newtonsoft.Json.Converters.IsoDateTimeConverter timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter(); //这里使用自定义日期格式,如果不使用的话,默认是ISO8601格式 timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; String result = Newtonsoft.Json.JsonConvert.SerializeObject(stu, Newtonsoft.Json.Formatting.None, timeConverter); Console.WriteLine(result); Console.ReadLine();
结果是:{"Id":1,"Name":"zhangsan","BirthDay":"2016-08-03 17:32:03"}
时间: 2024-10-17 05:19:46