Newtonsoft.Json利用IsoDateTimeConverter处理日期类型

来源:互联网 发布:电商行业数据分析 编辑:程序博客网 时间:2024/06/05 03:59

Newtonsoft.Json.dll来序列化反序列化对象和Json字符串时非常方便

但是如果对象中存在日期类型属性时,序列化后格式是

{"UserId":1,"UserName":"李 刚","CreateDate":"\/Date(353521211984)\/"}

其中日期会被转换成Date(353521211984),其中Date代表的是日期,353521211984是毫秒

上面的格式看起来非常不方便,所以我们应该转换成普通的日期格式如:2013-01-15 12:13:14

Newtonsoft.Json里面有一个类IsoDateTimeConverter可以转换日期,下面是转换的方法

/// 将一个对象序列化成一个JSON字符串public static string SerializeObject(T obj){IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();//这里使用自定义日期格式,如果不使用的话,默认是ISO8601格式timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";string serialStr = JsonConvert.SerializeObject(obj, Formatting.Indented, timeConverter);return serialStr;}

利用IsoDateTimeConverter转换后结果

{"UserId":1,"UserName":"李 刚","CreateDate":"2013-01-15 12:13:14"}

上面是序列化一个对象,下面是序列化对象集合

/// 将一个对象集合序列化成一个JSON字符串public static string SerializeObject(List list){IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();//这里使用自定义日期格式,如果不使用的话,默认是ISO8601格式timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";string serialStr = JsonConvert.SerializeObject(list, Formatting.Indented, timeConverter);return serialStr;}
注意: timeConverter.DateTimeFormat只有Newtonsoft.Json.dll(3.5)版本才有,2.0的没有

在使用时候,注意查看ewtonsoft.Json.dll的版本跟当前程序的.net 版本是否相同,不然会报下面错误:

未能加载文件或程序集“Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b9a188c8922137c6”或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040) 

Newtonsoft.Json.dll下载地址:

http://json.codeplex.com/releases/view/97986


引用资料:

http://www.sweiku.com/newtonsoft-json-isodatetimeconverter.html


原创粉丝点击