加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:24:39 所属栏目:百科 来源:网络整理
导读:Newtonsoft.Json.dll来序列化反序列化对象和Json字符串时非常方便 但是如果对象中存在日期类型属性时,序列化后格式是 {"UserId":1,"UserName":"李 刚","CreateDate":"/Date(353521211984)/"} 其中日期会被转换成Date(353521211984),其中Date代表的是日期

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,"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,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读