json2.js和wcf传递Date对象问题

在使用jquery和wcf通信的时候,遇到了通过json传递Date对象的问题.通过观察发现wcf返回到浏览器中的json字符串 是 "\/Date(1231231323+0800)\/" 形式。前面的数字1231231323是GMT 时区中自1970 年1 月1 日午夜以来按正常时间(非夏令时)经过的毫秒数.

所以可以取出该数字得到Date对象


var dateStr =  "\/Date(1231231323+0800)\/";

var date =new Date(parseInt( dataStr.substring(6,dataStr.length-2) ));

当然要想把客户端的Date对象通过json字符串传递给wcf也必须把Date对象格式化成 "\/Date(1231231323+0800)\/"形式的字符串

var date =new Date();
var dateStr = "\/Date("+date.getTime()+"+0800)\/"

 我使用的json2.js中的JSON.stringify和JSON.parse来完成js对象和json字符串之间转换的。但是这两个方法默认的转换是按照ISO strings形式转换的

查看json2.js可以发现下面代码段

        Date.prototype.toJSON = function (key) {

            
return this.getUTCFullYear()   + '-' +
                 f(
this.getUTCMonth() + 1+ '-' +
                 f(
this.getUTCDate())      + 'T' +
                 f(
this.getUTCHours())     + ':' +
                 f(
this.getUTCMinutes())   + ':' +
                 f(
this.getUTCSeconds())   + 'Z';
        }
;

 所以大家如果只需要个wcf通信的话可以把这个方法修改下返回wcf形式的字符串,这样直接调用JSON.stringify(data)

就ok了,不用再特别处理时间对象了。

        Date.prototype.toJSON = function(key) {
            
return "\/Date(" + this.getTime() + "+0800)\/";
        }
;

 现在看下如何让JSON.parse方法也自动处理好服务器端返回的json时间字符串,我们知道JSON.parse方法第二个参数是一个回调函数,可以用来遍历处理wcf返回json对象的属性。所以我们可以这样来解析wcf返回的json字符串

JSON.parse(data,function(key, value) {
        
if (typeof value == "string" && value.indexOf("\/Date("== 0{
            
var s = value.substring(6, value.length - 2);
            
return new Date(parseInt(s));
        }

            
return value;
    }
)

 这里判断value是时间的字符串不是很严格,大家可以自己修改下。

但是这样每次调用都传入该函数也挺烦人的,反正我只和wcf通信,于是也可以修改json2.js

找到下面的代码段

      JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
//
 a JavaScript value if the text is a valid JSON text.

            
var j;

            
}

 然后再parse方法的前面加上下面代码

  JSON.parse = function(text, reviver) {
            
// 修改×××××××××××××××××××××××××××
            if (reviver == undefined) {
                reviver 
= function(key, value) {
                    
if (typeof value == "string" && value.indexOf("\/Date("== 0{
                        
var s = value.substring(6, value.length - 2);
                        
return new Date(parseInt(s));
                    }

                    
return value;
                }

            }
  // 修改×××××××××××××××××××××××××××


            
// The parse method takes a text and an optional reviver function, and returns
            // a JavaScript value if the text is a valid JSON text.

            
var j;

}

这样当我们就不需要每次传入 第二个参数reviver 回调函数了。

我修改过的json2.js文件 https://files.cnblogs.com/xhan/json2Xhan.js

原文地址:https://www.cnblogs.com/xhan/p/1446406.html