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

asp.net – 如何强制netwtonsoft json序列化程序序列化datetime

发布时间:2020-12-15 19:41:52 所属栏目:asp.Net 来源:网络整理
导读:我使用Newtonsoft的Json 当我serialze日期时间属性我得到json响应为: ..."CreatedOn":"/Date(1317303882420+0500)/",... 我想它在简单的字符串 ..."createdOn": "2011-05-05 14:03:07",... 而我的类属性是DateTime,我如何可以强制序列化它作为字符串,因
我使用Newtonsoft的Json
当我serialze日期时间属性我得到json响应为:
..."CreatedOn":"/Date(1317303882420+0500)/",...

我想它在简单的字符串

..."createdOn": "2011-05-05 14:03:07",...

而我的类属性是DateTime,我如何可以强制序列化它作为字符串,因为我们可以添加属性更改属性名称为

[JsonProperty("id")]
        public int ProductID { get; set; }

是否有类似的方法强制一个DateTime属性序列化为字符串?

解决方法

从James Newton-King在StackOverflow上发表的帖子看,你可以这样做。
string isoJson = JsonConvert.SerializeObject(this,new IsoDateTimeConverter());
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}

参考答案:
Parsing JSON DateTime from Newtonsoft’s JSON Serializer

这里也是关于Json.NET和日期的文档:
Serializing Dates in JSON

下面是使用DateTimeFormat属性自定义输出的示例:

return JsonConvert.SerializeObject(this,Formatting.None,new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });

(编辑:李大同)

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

    推荐文章
      热点阅读