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

查看:21
本文介绍了如何解析 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 中从 this 创建一个 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") 或一个来自 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.

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

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