http://www.cnblogs.com/yubinfeng/p/4637165.html
Serialization,Deserialize
程序集:System.Web.Extensions.dll
命名空间:System.Web.Script.Serialization
类:Serialization,Deserialize
///<summary>/// 类:武林高手 /// MartialArtsMaster ///</summary> [DataContract] publicclass MartialArtsMaster { [DataMember] ///<summary>/// 编号 ///</summary>publicint id { get; set; } [DataMember] ///<summary>/// 姓名 ///</summary>publicstring name { get; set; } [DataMember] ///<summary>/// 年龄 ///</summary>publicint age { get; set; } [DataMember] ///<summary>/// 门派 ///</summary>publicstring menpai { get; set; } [DataMember] ///<summary>/// 武学 ///</summary>public List<Kongfu> kongFu { get; set; } ///<summary>/// 级别 ///</summary>publicint level { get; set; } } ///<summary>/// 类:武学 /// Kongfu ///</summary>[DataContract] publicclass Kongfu { [DataMember] ///<summary>/// 武学名称 ///</summary>publicstring kongfuName { get; set; } [DataMember] ///<summary>/// 杀伤力 ///</summary>publicint lethality { get; set; } }
List<MartialArtsMaster> masterList = new List<MartialArtsMaster>(); //增加几个武林高手 masterList.Add(new MartialArtsMaster() { id = 1, name = "令狐冲", age = 23, menpai = "华山", kongFu = new List<Kongfu>() { new Kongfu() { kongfuName = "独孤九剑", lethality = 100 }, new Kongfu() { kongfuName = "易筋经", lethality = 100 } }, level = 10 }); masterList.Add(new MartialArtsMaster() { id = 2, name = "黄药师", age = 55, menpai = "桃花岛", kongFu = new List<Kongfu>() { new Kongfu() { kongfuName = "弹指神通", lethality = 100 } }, level = 10 }); masterList.Add(new MartialArtsMaster() { id = 3, name = "段誉", age = 20, menpai = "天龙寺", kongFu = new List<Kongfu>() { new Kongfu() { kongfuName = "凌波微步", lethality = 100 }, new Kongfu() { kongfuName = "六脉神剑", lethality = 100 } }, level = 10 }); masterList.Add(new MartialArtsMaster() { id = 4, name = "乔峰", age = 33, menpai = "丐帮", kongFu = new List<Kongfu>() { new Kongfu() { kongfuName = "降龙十八掌", lethality = 100 }, new Kongfu() { kongfuName = "打狗棒法", lethality = 100 } }, level = 10 });
Serialization 序列化
//程序集:System.Web.Extensions.dll //命名空间:System.Web.Script.Serialization //类:Serialization,Deserialize JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); //执行序列化string strJson2 = jsonSerializer.Serialize(masterList); Console.WriteLine(strJson2);
Deserialize 反序列化
//执行反序列化 JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); List<MartialArtsMaster> newMasterList = jsonSerializer.Deserialize<List<MartialArtsMaster>> (strJson2); string result = String.Empty; Func<List<Kongfu>, string> kongFu = delegate (List<Kongfu> kongfu) { string kflist = String.Empty; kongfu.ForEach(m => kflist += "武功名称:" + m.kongfuName + ";杀伤力" + m.lethality + "\n"); return kflist; }; newMasterList.ForEach(m => result += "大侠编号:" + m.id + " 大侠名字:" + m.name + " 年龄:" + m.age + " 门派:" + m.menpai + " \n所学武功:\n" + kongFu(m.kongFu)); Console.WriteLine(result);
时间: 2024-10-11 07:00:56