Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

asp.net - how to force netwtonsoft json serializer to serialize datetime property to string?

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Referenced answer: Parsing JSON DateTime from Newtonsoft's JSON Serializer

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...