我有一个控制器动作,它有效地简单地返回模型的JsonResult。所以,在我的方法中,我有如下内容:
return new JsonResult(myModel);
这很有效,除了一个问题。在模型中有一个日期属性,这似乎在Json结果中返回,如下所示:
"\/Date(1239018869048)\/"
我应该如何处理日期,以便它们以我所需的格式返回?或者我如何处理脚本上面的这种格式?
我有一个控制器动作,它有效地简单地返回模型的JsonResult。所以,在我的方法中,我有如下内容:
return new JsonResult(myModel);
这很有效,除了一个问题。在模型中有一个日期属性,这似乎在Json结果中返回,如下所示:
"\/Date(1239018869048)\/"
我应该如何处理日期,以便它们以我所需的格式返回?或者我如何处理脚本上面的这种格式?
当前回答
你可以使用这个方法:
String.prototype.jsonToDate = function(){
try{
var date;
eval(("date = new " + this).replace(/\//g,''));
return date;
}
catch(e){
return new Date(0);
}
};
其他回答
在knockoutjs中处理日期的更好方法是使用moment库并像boss一样处理日期。您可以轻松地处理/Date(-62135578800000)/这样的日期。不需要担心如何在控制器中序列化日期。
function jsonToDate(date,format) {
return moment(date).format(format);
}
像这样使用它
var formattedDate = jsonToDate(date,'MM/DD/YYYY')
Momentjs支持大量的日期时间格式和日期实用函数。
让我们扩展一下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()的文档
不是没有原因,而是还有别的办法。首先,构造LINQ查询。然后,构造枚举结果的查询,并应用适合您的格式类型。
var query = from t in db.Table select new { t.DateField };
var result = from c in query.AsEnumerable() select new { c.DateField.toString("dd MMM yyy") };
我不得不说,额外的步骤很烦人,但效果很好。
我发现创建一个新的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;
}