如何强制 netwtonsoft json 序列化程序将日期时间属性序列化为字符串? [英] how to force netwtonsoft json serializer to serialize datetime property to string?

查看:13
本文介绍了如何强制 netwtonsoft json 序列化程序将日期时间属性序列化为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Newtonsoft 的 Json当我序列化日期时间属性时,我得到的 json 响应为:

I am using Newtonsoft's Json when i serialze a date time property i get the json response as:

..."CreatedOn":"/Date(1317303882420+0500)/",...

我希望它是简单的字符串

i want it to be in simple string as

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

虽然我的类属性是 DateTime,但我如何强制将其序列化为字符串,因为我们可以添加属性以将属性名称更改为

while my class property is DateTime, how can i force to serialze it as string, as we can add attribute to change the property name as

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

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

is there a similar way to force a DateTime property to serialize to string??

推荐答案

来自 James Newton-King 在 StackOverflow 上发表的帖子,看起来您可以做到这一点.

From a post made by James Newton-King on StackOverflow, it looks like you can do this.

string isoJson = JsonConvert.SerializeObject(this, new IsoDateTimeConverter());
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}    

参考答案:从 Newtonsoft 的 JSON Serializer 解析 JSON DateTime

还有关于 Json.NET 和日期的文档:在 JSON 中序列化日期

Also here is the documentation on Json.NET and dates: Serializing Dates in JSON

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

Here is an example of using the DateTimeFormat property to customize the output:

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

这篇关于如何强制 netwtonsoft json 序列化程序将日期时间属性序列化为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆