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
918 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - ASP MVC 4 JsonResult how to use ISO 8601 dates?

I have just installed ASP MVC 4 and my JSON dates are still coming back in the old format {"timestamp":"/Date(1348070400000)/"}.

I was under the impression that they should be coming back in the format 2012-02-18T00:54:06.8447642Z without me doing anything.

Note: JSON.NET is now an integral part of ASP.NET Web API so you can just us it out of the box.

My controller looks something like this

public JsonResult Test()
{
    return Json(new {timestamp = DateTime.Now()}, JsonRequestBehavior.AllowGet);
}

How can I get this to work? Do I need to make a change in my Global.asax.cs or Web.config?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I was under the impression that they should be coming back in the format 2012-02-18T00:54:06.8447642Z without me doing anything.

That's true only for ASP.NET Web API (ApiControllers). But standard ASP.NET MVC controller actions returning JsonResults still use the JavaScriptSerializer. So if you want to use ISO 8601 dates you could swap this serializer by JSON.NET by writing a custom action result. Just add the proper converter to the settings used by the serializer:

SerializerSettings.Converters.Add(new IsoDateTimeConverter());

You might be asking why they didn't implement JSON.NET for standard controllers. I guess it's for compatibility reasons as that would be an important breaking change. But I would probably have made JSON.NET the default serializer with a fallback option for those upgrading their existing applications.


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

...