ASP.NET MVC JsonResult日期格式

 2023-02-17    387  

问题描述

我有一个控制器操作,该操作有效地简单地返回了我的模型的jsonresult.因此,在我的方法中,我有以下内容:

return new JsonResult(myModel);

这很好,除了一个问题.该模型中有一个日期属性,似乎在JSON结果中返回了这样的属性:

ASP.NET MVC JsonResult日期格式

"\/Date(1239018869048)\/"

我应该如何处理日期,以便以我需要的格式返回它们?或如何在脚本中处理以上格式?

推荐答案

只是为了扩展 Casperone的答案…./p>

json Spec 不考虑日期值. MS必须打电话,他们选择的道路是在JavaScript表示字符串表示中利用一个小技巧:字符串文字”/”与” \/”相同,并且字符串字面的字体将永远从不/em>序列化为” \/”(甚至必须映射到” \\/”).

参见/library/bb299886.aspx#intro_to_json_topic2 为更好的解释(向下滚动到”从javascript文字到json”)

JSON的痛点之一是
缺乏日期/时间文字.许多
人们感到惊讶和失望
首先学习这件事
遇到JSON.简单的解释
(是否安慰)没有
日期/时间的字面意思是JavaScript
也从来没有一个:支持
JavaScript中的日期和时间值是
完全提供日期
目的.大多数使用JSON的应用程序
因此,作为数据格式,通常
倾向于使用字符串或
表达日期和时间的号码
值.如果使用了字符串,您可以
通常期望它在ISO中
8601格式.如果使用数字,
相反,该值通常为
指的是
通用协调的毫秒
时间(UTC)自时代以来,时代为
定义为1970年1月1日午夜
(世界标准时间).再次,这仅仅是
会议,而不是JSON的一部分
标准.如果您要交换数据
使用另一个应用程序,您将
需要检查其文档以查看
它如何编码日期和时间值
在JSON字面意义上.例如,
Microsoft的ASP.NET AJAX都不使用
描述的惯例.相当,
它将.NET DATETIME值编码为
json string,其中的内容
字符串为/日期(ticks)/以及
tick代表毫秒以来
时代(UTC).因此1989年11月29日,
4:55:30 AM,在UTC中编码为
” \/date(628318530718)\/”.

解决方案就是将其解析出来:

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

但是,我听说有一个设置可以使序列化器使用new Date(xxx)语法输出DateTime对象.我会尝试挖掘出来.


JSON.parse()的第二个参数接受a reviver函数,在返回之前,处方的值最初产生的值.

.

这是日期的示例:

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()

其他推荐答案

这是我在JavaScript中的解决方案 – 非常像JPOT的解决方案,但是更短(可能更快一点):

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

” value.substr(6)”取出”/date(“部分,parseint函数忽略了在末尾发生的非数字字符.

编辑:我有意省略了radix(parseint的第二个论点);参见下面我的评论.另外,请注意,ISO-8601日期比这种旧格式优先 – 因此,这种格式通常不应该用于新开发.

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

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

其他推荐答案

有很多答案可以处理客户端,但是如果需要,您可以更改输出服务器端.

有几种方法可以解决这个问题,我将从基础知识开始.您必须将JSONRESULT类子级划分并覆盖执行者方法.从那里您可以采用几种不同的方法来更改序列化.

方法1:
The default implementation uses the JsonScriptSerializer .如果您查看文档,则可以使用registerConverters方法添加自定义 javascriptConverters .但是,有一些问题:javascriptConverter序列到词典,也就是说,它需要一个对象并序列到JSON字典.为了使对象序列化到字符串,需要一些黑客,请参见 post .这个特殊的黑客也将逃脱字符串.

public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

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

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            // Use your custom JavaScriptConverter subclass here.
            serializer.RegisterConverters(new JavascriptConverter[] { new CustomConverter });

            response.Write(serializer.Serialize(Data));
        }
    }
}

方法2(推荐):
第二种方法是从覆盖的jsonresult开始,然后使用另一个JSON序列化器,就我而言, json.net 序列化器.这不需要方法.

public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

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

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            // Using Json.NET serializer
            var isoConvert = new IsoDateTimeConverter();
            isoConvert.DateTimeFormat = _dateFormat;
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
        }
    }
}

用法示例:

[HttpGet]
public ActionResult Index() {
    return new CustomJsonResult { Data = new { users=db.Users.ToList(); } };
}

其他学分:
詹姆斯·牛顿 – 金

以上所述是小编给大家介绍的ASP.NET MVC JsonResult日期格式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!

原文链接:https://77isp.com/post/34171.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。