日期:2014-05-20 浏览次数:21046 次
<html> <head> <script src="MicrosoftAjax.js" type="text/javascript"></script> <script src="TestSerializer.js" type="text/javascript"></script> <script type="text/javascript"> </script> </head> <body> <span>序列化:</span><div id="t1">Answer</div> <span>反序列化:</span><div id="t2">Answer</div> </body> </html>
TestSerializer = {}; TestSerializer.TestSerialize = function(){ var _div = $get("t1"); var _myObj1= new TestSerializer.TestObject(); _myObj1.set_Id("1");//只设置一个属性 _div.innerHTML = Sys.Serialization.JavaScriptSerializer.serialize(_myObj1); } TestSerializer.TestDeserialize = function(){ var _div1 = $get("t1"); var _div2 = $get("t2"); var _jsonRow = "{'_id':'1'}";//只传递一个属性 var _myObj2 = TestSerializer.TestObject.GetFromJson(_jsonRow); _div2.innerHTML="Id:" + _myObj2.get_Id()+";Name:"+_myObj2.get_Name(); } TestSerializer.TestObject = function(){ //构造函数为所有字段设定默认值 this._id = ""; this._name = ""; }; TestSerializer.TestObject.prototype={ get_Id:function(){return this._id;} ,set_Id:function(pNew){this._id = pNew;} ,get_Name:function(){return this._name;} ,set_Name:function(pNew){this._name=pNew;} } TestSerializer.TestObject.GetFromJson = function(pJsonRow){ var _jsonObj = Sys.Serialization.JavaScriptSerializer.deserialize(pJsonRow); var _newObj = new TestSerializer.TestObject(); //拷贝所有存在的字段 if (_jsonObj._id) {_newObj.set_Id(_jsonObj._id);} if(_jsonObj._name){_newObj.set_Name(_jsonObj._name);} return _newObj; } Sys.Application.add_load(PageLoadHandler); function PageLoadHandler(){ TestSerializer.TestSerialize(); TestSerializer.TestDeserialize(); } TestSerializer.TestObject.registerClass('TestSerializer.TestObject',null);