我有一个控制器动作,它有效地简单地返回模型的JsonResult。所以,在我的方法中,我有如下内容:

return new JsonResult(myModel);

这很有效,除了一个问题。在模型中有一个日期属性,这似乎在Json结果中返回,如下所示:

"\/Date(1239018869048)\/"

我应该如何处理日期,以便它们以我所需的格式返回?或者我如何处理脚本上面的这种格式?


当前回答

它返回服务器日期格式。你需要定义自己的函数。

function jsonDateFormat(jsonDate) {
  // Changed data format;
  return (new Date(parseInt(jsonDate.substr(6)))).format("mm-dd-yyyy / h:MM tt");
};

其他回答

让我们扩展一下casperOne的答案。

JSON规范没有说明Date值。MS不得不进行调用,他们选择的路径是利用javascript字符串表示中的一个小技巧:字符串字面量“/”与“\/”相同,字符串字面量永远不会被序列化为“\/”(甚至“\/”也必须映射为“\\/”)。

参见http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2获得更好的解释(向下滚动到“从JavaScript文字到JSON”)

One of the sore points of JSON is the lack of a date/time literal. Many people are surprised and disappointed to learn this when they first encounter JSON. The simple explanation (consoling or not) for the absence of a date/time literal is that JavaScript never had one either: The support for date and time values in JavaScript is entirely provided through the Date object. Most applications using JSON as a data format, therefore, generally tend to use either a string or a number to express date and time values. If a string is used, you can generally expect it to be in the ISO 8601 format. If a number is used, instead, then the value is usually taken to mean the number of milliseconds in Universal Coordinated Time (UTC) since epoch, where epoch is defined as midnight January 1, 1970 (UTC). Again, this is a mere convention and not part of the JSON standard. If you are exchanging data with another application, you will need to check its documentation to see how it encodes date and time values within a JSON literal. For example, Microsoft's ASP.NET AJAX uses neither of the described conventions. Rather, it encodes .NET DateTime values as a JSON string, where the content of the string is /Date(ticks)/ and where ticks represents milliseconds since epoch (UTC). So November 29, 1989, 4:55:30 AM, in UTC is encoded as "\/Date(628318530718)\/".

一个解决办法就是把它解析出来:

value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));

然而,我听说在某个地方有一个设置,可以让序列化器用新的Date(xxx)语法输出DateTime对象。我试着把它挖出来。


JSON.parse()的第二个参数接受一个恢复函数,其中规定了在返回值之前最初是如何生成值的。

下面是一个关于date的例子:

var parsed = JSON.parse(data, function(key, value) {
  if (typeof value === 'string') {
    var d = /\/Date\((\d*)\)\//.exec(value);
    return (d) ? new Date(+d[1]) : value;
  }
  return value;
});

查看JSON.parse()的文档

请看这个帖子:

http://forums.asp.net/p/1038457/1441866.aspx#1441866

基本上,虽然Date()格式是有效的javascript,但它不是有效的JSON(有区别)。如果您想要使用旧格式,您可能必须自己创建一个外观并转换值,或者找到一种方法来获取JsonResult中类型的序列化器,并让它使用日期的自定义格式。

下面是我的Javascript解决方案——非常像JPot,但更短(可能更快一点):

value = new Date(parseInt(value.substr(6)));

"value.substr(6)"去掉"/Date("部分,parseInt函数忽略出现在结尾的非数字字符。

编辑:我故意省略了基数(parseInt的第二个参数);请看我下面的评论。另外,请注意ISO-8601日期比这种旧格式更受欢迎——因此这种格式通常不应该用于新的开发。

对于ISO-8601格式的JSON日期,只需将字符串传递给Date构造函数:

var date = new Date(jsonDate); //no ugly parsing needed; full timezone support

我发现创建一个新的JsonResult并返回它是不令人满意的-必须用返回新的MyJsonResult {Data = obj}替换所有返回Json(obj)的调用是一种痛苦。


所以我想,为什么不只是劫持JsonResult使用ActionFilter:

public class JsonNetFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is JsonResult == false)
        {
            return;
        }

        filterContext.Result = new JsonNetResult(
            (JsonResult)filterContext.Result);
    }

    private class JsonNetResult : JsonResult
    {
        public JsonNetResult(JsonResult jsonResult)
        {
            this.ContentEncoding = jsonResult.ContentEncoding;
            this.ContentType = jsonResult.ContentType;
            this.Data = jsonResult.Data;
            this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
            this.MaxJsonLength = jsonResult.MaxJsonLength;
            this.RecursionLimit = jsonResult.RecursionLimit;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var isMethodGet = string.Equals(
                context.HttpContext.Request.HttpMethod, 
                "GET", 
                StringComparison.OrdinalIgnoreCase);

            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
                && isMethodGet)
            {
                throw new InvalidOperationException(
                    "GET not allowed! Change JsonRequestBehavior to AllowGet.");
            }

            var response = context.HttpContext.Response;

            response.ContentType = string.IsNullOrEmpty(this.ContentType) 
                ? "application/json" 
                : this.ContentType;

            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }

            if (this.Data != null)
            {
                response.Write(JsonConvert.SerializeObject(this.Data));
            }
        }
    }
}

这可以应用于任何返回JsonResult以使用JSON的方法。网:

[JsonNetFilter]
public ActionResult GetJson()
{
    return Json(new { hello = new Date(2015, 03, 09) }, JsonRequestBehavior.AllowGet)
}

它会回应

{"hello":"2015-03-09T00:00:00+00:00"}

根据需要!


你可以,如果你不介意在每个请求时调用is比较,添加这个到你的FilterConfig:

// ...
filters.Add(new JsonNetFilterAttribute());

所有的JSON都将被JSON序列化。Net而不是内置的JavaScriptSerializer。

这不是最优雅的方式,但对我来说很管用:

var ms = date.substring(6, date.length - 2);
var newDate = formatDate(ms);


function formatDate(ms) {

    var date = new Date(parseInt(ms));
    var hour = date.getHours();
    var mins = date.getMinutes() + '';
    var time = "AM";

    // find time 
    if (hour >= 12) {
        time = "PM";
    }
    // fix hours format
    if (hour > 12) {
        hour -= 12;
    }
    else if (hour == 0) {
        hour = 12;
    }
    // fix minutes format
    if (mins.length == 1) {
        mins = "0" + mins;
    }
    // return formatted date time string
    return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + hour + ":" + mins + " " + time;
}