JavaScript对象也玩序列化和反序列化

2010-05-25 经过笔者测试,改方法无法使用!经测试可使用的方法见《Json2.js手册

序列化,把JavaScript对象转换为字符串:

Object.prototype.Serialize = function()
{
    var type = __typeof__(this);
    switch(type)
    {
         case 'Array' :
         {
              var strArray = '[';
              for ( var i=0 ; i < this.length ; ++i )
              {
                   var value = '';
                   if ( this[i] )
                   {
                        value = this[i].Serialize();
                   }
                   strArray += value + ',';
              }
              if ( strArray.charAt(strArray.length-1) == ',' )
              {
                   strArray = strArray.substr(0, strArray.length-1);
              }
              strArray += ']'; 
              return strArray;
         }
         case 'Date' :
         {
              return 'new Date(' + this.getTime() + ')';
         }
         case 'Boolean' :
         case 'Function' :
         case 'Number' :
         case 'String' :
         {
              return this.toString();
         }
         default :
         {
              var serialize = '{';
              for ( var key in this )
              {
                   if ( key == 'Serialize' ) continue;
                   var subserialize = 'null';
                   if ( this[key] != undefined )
                   {
                        subserialize = this[key].Serialize();
                   }
                   serialize += '\r\n' + key + ' : ' + subserialize + ',';
              }
              if ( serialize.charAt(serialize.length-1) == ',' )
              {
                   serialize = serialize.substr(0, serialize.length-1);
              }
              serialize += '\r\n}';
              return serialize;
         }
    }
};
    其实就是Array和Object的属性比较的麻烦,需要递归的做这个Serialize操作。不过需要注意,Serialize方法就不需要被序列化出来了。下面是测试示例,不过这个序列化方法没有对环状引用做检查,能序列化的对象很有限。

var obj1 = [];
alert(obj1.Serialize());

var obj2 = [1,[2,[3,[4,[5,[6,[7,[8,[9,[0]]]]]]]]]];
alert(obj2.Serialize());

var obj3 =
    {
         Properties1 : 1, Properties2 : '2', Properties3 : [3],
         Method1 : function(){ return this.Properties1 + this.Properties3[0];},
         Method2 : function(){ return this.Preperties2; }
    };
alert(obj3.Serialize()); 

var obj4 = [null, 1, 'string', true, function(){return 'keke';}, new Object()];
alert(obj4.Serialize());

修改对象原型,增加一个方法!
反序列化……eval一下

  →关键词
  →添加评论
标题: 
署名: 
留言内容: 
验证码:  点击可刷新验证码
    0条记录,分0页,当前正在浏览第1页。
    返回文章表列 关闭本页