資源描述:
《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屬性標(biāo)記不序列化公共屬性或公共字段。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é)定的一部分且沒有進(jìn)行序列化,DataMember:定義序列化屬性參數(shù),使用DataMem
6、ber屬性標(biāo)記字段必須使用DataContract標(biāo)記類否則DataMember標(biāo)記不起作用。代碼[DataContract]publicclassPeople{[DataMember(Name="id")]publicintId{get;set;}[IgnoreDataMember]publicstringName{get;set;}}輸出結(jié)果:{"id":1}