问题描述
我正在使用消耗JSON Web Services的HTML5/JavaScript构建Windows 8 Metro应用程序(又名现代UI样式"或"Windows Store应用程序"),并且遇到以下问题:采用哪种格式我的JSON Web服务是否应该为Windows 8 Metro JSON.parse 方法序列化日期以反序列化日期类型中的日期?
I'm building a Windows 8 Metro app (aka "Modern UI Style" or "Windows Store app") in HTML5/JavaScript consuming JSON Web Services and I'm bumping into the following issue: in which format should my JSON Web Services serialize dates for the Windows 8 Metro JSON.parse method to deserialize those in a date type?
我尝试过:
- 使用 ISO-8601格式发送日期,(JSON.parse返回一个字符串),
- 发送日期,例如"/Date(1198908717056)/"作为在此处解释(结果相同).
- sending dates using the ISO-8601 format, (JSON.parse returns a string),
- sending dates such as "/Date(1198908717056)/" as explained here (same result).
我开始怀疑Windows 8的JSON.parse方法支持日期,即使解析其自己的JSON.stringify方法的输出不返回日期类型也是如此.
I'm starting to doubt that Windows 8's JSON.parse method supports dates as even when parsing the output of its own JSON.stringify method does not return a date type.
示例:
var d = new Date(); // => a new date
var str = JSON.stringify(d); // str is a string => "\"2012-07-10T14:44:00.000Z\""
var date2 = JSON.parse(str); // date2 is a string => "2012-07-10T14:44:00.000Z"
推荐答案
这是我以通用方式进行此操作的方式(尽管我宁愿找到Windows 8 JSON开箱即用支持的格式.解析方法):
Here's how I got this working in a generic way (though it I'd rather find a format supported out-of-the-box by Windows 8's JSON.parse method):
在服务器上,我使用以下命令对字符串进行序列化
On the server, I'm serializing my strings using:
date1.ToString("s");
这将使用始终相同的ISO 8601日期格式,而不考虑所使用的区域性或所提供的格式提供者(有关详细信息,请参见此处).
This uses the ISO 8601 date format which is always the same, regardless of the culture used or the format provider supplied (see here for more information).
在客户端,我为JSON.parse指定了一个"reviver"回调,该回调使用正则表达式查找日期并将其自动转换为日期对象.
On the client-side, I specified a "reviver" callback to JSON.parse which looks for dates using a regexp and converts them into a date object automatically.
最后,反序列化的对象将包含实际的JavaScript日期类型,而不是字符串.
In the end, the deserialized object will contain actual JavaScript date types and not strings.
这是一个代码示例:
var responseResult = JSON.parse(request.responseText, function dateReviver(key, value) {
if (typeof value === 'string') {
var re = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)$/
var result = re.exec(value);
if (result) {
return new Date(Date.UTC(+result[1], +result[2] - 1, +result[3], +result[4],+result[5], +result[6]));
}
});
希望这会有所帮助,卡尔
Hope this helps,Carl
这篇关于如何使用Windows 8 JSON.parse将JSON文本反序列化为日期类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!