如何强制netwtonsoft JSON序列为datetime属性序列化到字符串? [英] how to force netwtonsoft json serializer to serialize datetime property to string?

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

问题描述

我使用Newtonsoft的的Json
当我serialze日期时间属性我得到的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", ...

而我的类属性是日期时间,我怎么能强制serialze它作为字符串,因为我们可以添加属性来更改属性名称

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??

推荐答案

这是由詹姆斯·牛顿国王在计算器上发了一个帖子,看起来你可以做到这一点。

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

参考答案:
<一href=\"http://stackoverflow.com/questions/668488/parsing-json-datetime-from-newtonsofts-json-serializer\">Parsing JSON日期时间从Newtonsoft的JSON序列

另外这里是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序列为datetime属性序列化到字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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