JSON进阶六-自动组装
2010-09-14 13:40:37 来源:WEB开发网核心提示: 可以看出除添加和删除动态行外,JSON的提取和绑定的代码是非常简单,JSON进阶六-自动组装(4),C#: public partial class ExampleTwo : System.Web.UI.Page{public string json = "[{"Nam
可以看出除添加和删除动态行外,JSON的提取和绑定的代码是非常简单。
C#:
public partial class ExampleTwo : System.Web.UI.Page { public string json = "[{"Name":"T31611","Student":[{"ID":1,"Name":"张三","Sex":1,"Score":" +"{"Chinese":33,"Math":44,"English":55}},{"ID":2,"Name":"李四","Sex":2," +""Score":{"Chinese":55,"Math":66,"English":77}},{"ID":3,"Name":"杨大"," +""Sex":1,"Score":{"Chinese":100,"Math":100,"English":100}}],"About":"这" +"个是反序列化的JSON绑定。"}]"; protected void Page_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(Request["tabs"])) { List<Class> cls = Request["tabs"].DeJSON<List<Class>>(); Response.Write(cls.ToJSON()); Response.End(); } } } public class Class { public string Name; public string About; public List<Student> Student; } public class Student { public int ID; public string Name; public int Sex; public Score Score; } public class Score { public decimal Chinese; public decimal Math; public decimal English; } using System.Collections.Generic; using System.Web.Script.Serialization; // Json序列化反序列化代码。 public static class Json { /// <summary> /// JSON序列化 /// </summary> /// <param name="obj"></param> /// <returns>JSON格式的字符串,或者JSON数组格式的字符串</returns> public static string ToJSON(this object obj) { JavaScriptSerializer serializer = new JavaScriptSerializer(); var st = serializer.Serialize(obj); return st; } /// <summary> /// JSON反序列化 /// </summary> /// <param name="T">反序列化成什么对象例如:hashtable</typeparam> /// <param name="json">json格式的字符串,包括json数组格式的字符串"[{"key":"0"},{"key":"1"}]"</param> /// <returns>指定泛型对象</returns> public static T DeJSON(this string json) { JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Deserialize (json); } }
后台代码是非常简单的,而且在结构没有发生颠覆性的改变的情况下,这块代码是不需要任何改变的。
文章来源:http://www.cnblogs.com/KangC/archive/2009/03/02/1359252.html
系列文章:
JSON进阶一-初识JSON
JSON进阶二-面向对象的JSON
JSON进阶三-JSON的几种调用形式
JSON进阶四-前后台交互之美
JSON进阶五-JS和WCF的交互
JSON进阶六-自动组装
JSON进阶七——AOP
更多精彩
赞助商链接