.net中解析json 之 DataContractJsonSerializer类

发布时间:2016-12-10 18:51:04 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了".net中解析json 之 DataContractJsonSerializer类",主要涉及到.net中解析json 之 DataContractJsonSerializer类方面的内容,对于.net中解析json 之 DataContractJsonSerializer类感兴趣的同学可以参考一下。

json 是轻量级的文本传输格式,一般用于前台和后台的数据交换 DataContractJsonSerializer是fm3.5中专门对json序列化和反序列化的类,以下是DataContractJsonSerializer的简单应用   假设客户端有个json对象,通过ajax传到后台,后台解析   代码如下: var people = [{ "UserName": "t1", "PassWord": "111111", "Sex": "男" },{ "UserName": "t2", "PassWord": "222222", "Sex": "女" }]; var url = "Default.aspx?people=" + escape(people.toJSONString()); request.open("POST", url, true); request.onreadystatechange = updatePage; request.send(null); toJSONString函数正常运行得引用json.js    <script src="json.js" type="text/javascript"></script>   后台代码: 新建测试类 testobj (testobj中的属性和客户端传递过来的一致) [DataContract]//序列化 public class TestObj { [DataMember] public string UserName { get; set; } [DataMember] public string PassWord { get; set; } [DataMember] public string Sex { get; set; } public TestObj(string u,string p,string s) { UserName = u; PassWord = p; Sex = s; } } 新建序列化和反序列化方法 //json 序列化 public static string ToJsJson(object item) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType()); using(MemoryStream ms=new MemoryStream()) { serializer.WriteObject(ms, item); StringBuilder sb = new StringBuilder(); sb.Append(Encoding.UTF8.GetString(ms.ToArray())); return sb.ToString(); } } //反序列化 public static T FromJsonTo<T>(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { T jsonObject = (T)ser.ReadObject(ms); return jsonObject; } } 调用: 反序列化json(解析)注:people即客户端传递过来 //获取json字符串 string jsonStr = Request["people"]; List<TestObj> obj = Json.FromJsonTo<List<TestObj>>(jsonStr); foreach (TestObj item in obj) { Response.Write(string.Format("UserName:{0},Password:{1},Sex:{2}/r/n", item.UserName, item.PassWord, item.Sex)); } Response.End(); 序列化成json字符串 List<TestObj> Users = new List<TestObj>(); Users.Add(new TestObj("t1", "1", "男")); Users.Add(new TestObj("t2", "2", "女")); string json = Json.ToJsJson(Users); Response.Write(json); Response.End(); 前台获取后台返回的json字符串: function updatePage() { if (request.readyState == 4) { if (request.status == 200) { var response = request.responseText; //转化成对象 //方法1 response = response.parseJSON(); //方法2 // response = eval("(" + response + ")"); //对象访问方式 document.getElementById("d1").innerHTML = response[1].Sex; //直接输出 // document.getElementById("d1").innerHTML = response; } } }

上一篇:java5的静态导入import static
下一篇:NSNotification的用法

相关文章

相关评论