json序列化與反序列化

json序列化與反序列化

ID:8976149

大?。?5.50 KB

頁數(shù):2頁

時間:2018-04-13

json序列化與反序列化_第1頁
json序列化與反序列化_第2頁
資源描述:

《json序列化與反序列化》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在應(yīng)用文檔-天天文庫。

1、方法一:引入System.Web.Script.Serialization命名空間使用JavaScriptSerializer類實現(xiàn)簡單的序列化序列化類:PersonnelpublicclassPersonnel{publicintId{get;set;}publicstringName{get;set;}}執(zhí)行序列化反序列化:代碼protectedvoidPage_Load(objectsender,EventArgse){Personnelpersonnel=newPersonnel();personnel.Id=1;personnel.Name="小白";Java

2、ScriptSerializerjsonSerializer=newJavaScriptSerializer();//執(zhí)行序列化stringr1=jsonSerializer.Serialize(personnel);//執(zhí)行反序列化Personnel_Personnel=jsonSerializer.Deserialize(r1);}r1輸出結(jié)果:{"Id":1,"Name":"小白"}可以使用ScriptIgnore屬性標記不序列化公共屬性或公共字段。publicclassPersonnel{[ScriptIgnore]publicintId{

3、get;set;}publicstringName{get;set;}}r1輸出結(jié)果:{"Name":"小白"}方法二:引入System.Runtime.Serialization.Json命名空間使用DataContractJsonSerializer類實現(xiàn)序列化序列化類:PeoplepublicclassPeople{publicintId{get;set;}publicstringName{get;set;}}執(zhí)行序列化反序列化代碼protectedvoidPage_Load(objectsender,EventArgse){Peoplepeople=newPeo

4、ple();people.Id=1;people.Name="小白";DataContractJsonSerializerjson=newDataContractJsonSerializer(people.GetType());stringszJson="";//序列化using(MemoryStreamstream=newMemoryStream()){json.WriteObject(stream,people);szJson=Encoding.UTF8.GetString(stream.ToArray());}//反序列化using(MemoryStreamms=

5、newMemoryStream(Encoding.UTF8.GetBytes(szJson))){DataContractJsonSerializerserializer=newDataContractJsonSerializer(typeof(People));People_people=(People)serializer.ReadObject(ms);}}szJson輸出結(jié)果:{"Id":1,"Name":"小白"}可以使用IgnoreDataMember:指定該成員不是數(shù)據(jù)協(xié)定的一部分且沒有進行序列化,DataMember:定義序列化屬性參數(shù),使用DataMem

6、ber屬性標記字段必須使用DataContract標記類否則DataMember標記不起作用。代碼[DataContract]publicclassPeople{[DataMember(Name="id")]publicintId{get;set;}[IgnoreDataMember]publicstringName{get;set;}}輸出結(jié)果:{"id":1}

當前文檔最多預(yù)覽五頁,下載文檔查看全文

此文檔下載收益歸作者所有

當前文檔最多預(yù)覽五頁,下載文檔查看全文
溫馨提示:
1. 部分包含數(shù)學(xué)公式或PPT動畫的文件,查看預(yù)覽時可能會顯示錯亂或異常,文件下載后無此問題,請放心下載。
2. 本文檔由用戶上傳,版權(quán)歸屬用戶,天天文庫負責整理代發(fā)布。如果您對本文檔版權(quán)有爭議請及時聯(lián)系客服。
3. 下載前請仔細閱讀文檔內(nèi)容,確認文檔內(nèi)容符合您的需求后進行下載,若出現(xiàn)內(nèi)容與標題不符可向本站投訴處理。
4. 下載文檔時可能由于網(wǎng)絡(luò)波動等原因無法下載或下載錯誤,付費完成后未能成功下載的用戶請聯(lián)系客服處理。