在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
过去我们使用JSON.net序列化一个对象,在asp.net3.5中已经集成了序列化对象为json的方法。
第一种方法: System.Runtime.Serialization.Json
下面为具体用法
声明一个需要输出JSON属性的类
View Code
1 public class topMenu
2 { 3 public string id { get; set; } 4 public string title { get; set; } 5 public string defaulturl { get; set; } 6 }
本例使它循环三次 利用上面GetJson方法序列化
View Code
1 topMenu t_menu = new topMenu()
2 { 3 id = "1", 4 title = "全局", 5 defaulturl = "123456" 6 }; 7 8 List<topMenu> l_topmenu = new List<topMenu>(); 9 for (int i = 0; i < 3; i++) 10 { 11 l_topmenu.Add(t_menu); 12 } 13 Response.Write(JsonHelper.GetJson<List<topMenu>>(l_topmenu));
输出结果为:
[{"defaulturl":"123456","id":"1","title":"全局"}, {"defaulturl":"123456","id":"1","title":"全局"}, {"defaulturl":"123456","id":"1","title":"全局"}]
下面利用上面ParseFromJson方法读取Json
View Code
1 string szJson = @"{""id"":""1"",""title"":""全局"",""defaulturl"":""123456""} ";
2 topMenu t_menu2 = JsonHelper.ParseFromJson<topMenu>(szJson); 3 Response.Write(t_menu2.title);
第二种方法 System.Web.Script.Serialization (引用System.Web.Extensions.dll)
还是用到上面方法中JSON属性的类 下面和上面方法中一样。循环三次就。序列化方式不一样
View Code
1 topMenu t_menu = new topMenu()
2 { 3 id = "1", 4 title = "全局", 5 defaulturl = "123456" 6 }; 7 8 List<topMenu> l_topmenu = new List<topMenu>(); 9 10 for (int i = 0; i < 3; i++) 11 { 12 l_topmenu.Add(t_menu); 13 }
下面用这种方式输出:
View Code
1 JavaScriptSerializer jss = new JavaScriptSerializer();
2 Response.Write( jss.Serialize(l_topmenu ));
[{"defaulturl":"123456","id":"1","title":"全局"}, {"defaulturl":"123456","id":"1","title":"全局"}, {"defaulturl":"123456","id":"1","title":"全局"}]
下面利用JavaScriptSerializer中的Deserialize方法读取Json
View Code
1 string szJson = @"{""id"":""1"",""title"":""全局"",""defaulturl"":""123456""} ";
2 topMenu toptabmenu = jss.Deserialize<topMenu>(szJson); 3 Response.Write( jss.Serialize(toptabmenu.title));
输出结果为:全局
综上。两种方法个有好处。一个比较灵活。一个较简洁
|
请发表评论