如何解析JSON以接收JavaScript中的Date对象? [英] How to parse JSON to receive a Date object in JavaScript?

查看:125
本文介绍了如何解析JSON以接收JavaScript中的Date对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON:

  \ / Date(1293034567877)\ / 

这是.NET代码的结果:

  var obj = DateTime.Now; 
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.Serialize(obj).Dump();

现在我面临的问题是如何从JavaScript中创建一个Date对象。
所有我可以找到的是令人难以置信的正则表达式解决方案(许多包含错误)。



很难相信没有优雅的解决方案,因为这是所有的JavaScrip,我的意思是JavaScript代码试图读取JSON(JavaScript对象符号),这应该是一个JavaScript代码,在这一刻,事实证明这不是因为JavaScript在这里做得不好。


$ b $我也看到一些我不能做的eval解决方案(除了被指出是安全威胁)。



真的没办法做一个优雅的方式?



相似的问题没有真正的答案:

如何用GWT解析ASP.NET JSON日期格式

解决方案

没有日期的标准JSON表示形式。你应该做@jAndy建议,而不是序列化一个 DateTime 只需发送RFC 1123日期字符串 ToString(r)或从Unix-epoch编号的秒数,或者您可以在JavaScript中使用的其他内容来构建日期


I have a following piece of JSON:

\/Date(1293034567877)\/

which is a result of this .NET code:

var obj = DateTime.Now;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.Serialize(obj).Dump();

Now the problem I am facing is how to create a Date object from this in JavaScript. All I could find was incredible regex solution (many containing bugs).

It is hard to believe there is no elegant solution as this is all in JavaScrip, I mean JavaScript code trying to read JSON (JavaScript Object Notation) which is supposed to be a JavaScript code and at this moment it turns out it's not cause JavaScript cannot do a good job here.

I've also seen some eval solutions which I could not make to work (besides being pointed out as security threat).

Is there really no way to do it in an elegant way?

Similar question with no real answer:
How to parse ASP.NET JSON Date format with GWT

解决方案

There is no standard JSON representation of dates. You should do what @jAndy suggested and not serialize a DateTime at all; just send an RFC 1123 date string ToString("r") or a seconds-from-Unix-epoch number, or something else that you can use in the JavaScript to construct a Date.

这篇关于如何解析JSON以接收JavaScript中的Date对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆