如何解析 JSON 以在 JavaScript 中接收 Date 对象?
我有以下一段 JSON:
I have a following piece of JSON:
/Date(1293034567877)/
这是 .NET 代码的结果:
which is a result of this .NET code:
var obj = DateTime.Now;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.Serialize(obj).Dump();
现在我面临的问题是如何在 JavaScript 中创建一个 Date 对象.我所能找到的只是令人难以置信的正则表达式解决方案(许多包含错误).
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).
很难相信没有优雅的解决方案,因为这一切都在 JavaScrip 中,我的意思是 JavaScript 代码试图读取 JSON(JavaScript 对象表示法),它应该是 JavaScript 代码,而现在事实证明它不是因为 JavaScript 在这方面做得不好.
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?
没有真正答案的类似问题:
如何使用 GWT 解析 ASP.NET JSON 日期格式
Similar question with no real answer:
How to parse ASP.NET JSON Date format with GWT
推荐答案
没有标准的 JSON 日期表示.你应该按照@jAndy 的建议去做,而不是序列化一个 DateTime
;只需发送 RFC 1123 日期字符串 ToString("r")
或 seconds-from-Unix-epoch 数字,或者您可以在 JavaScript 中使用的其他内容来构造 Date代码>.
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
.
相关文章