本篇文章主要是對Json序列化和反序列化方法進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助
代碼如下: /// <summary> /// Json序列化,用於發送到客戶端 /// </summary> public static string ToJsJson(this 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(); } } /// <summary> /// Json反序列化,用於接收客戶端Json後生成對應的對象 /// </summary> public static T FromJsonTo<T>(this string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T jsonObject = (T)ser.ReadObject(ms); ms.Close(); return jsonObject; } 實體類 代碼如下: [DataContract] public class TestObj { [DataMember] public string make { get; set; } [DataMember] public string model { get; set; } [DataMember] public int year { get; set; } [DataMember] public string color { get; set; } } ------------------javascript獲取Json-------------------- javascript調用測試代碼 代碼如下: $('#getJson').click(function() { $.ajax({ url: "getJsonHandler.ashx", type: 'GET', data: {}, dataType: 'json', timeout: 1000, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus) }, success: function(result) { alert(result.make); alert(result.model); alert(result.year); alert(result.color); } }); }); C#後台生成代碼 代碼如下: public class getJsonHandler: IHttpHandler { public void ProcessRequest(HttpContext context) { TestObj obj = new TestObj(); obj.make = "Make is Value"; obj.model = "Model is Value"; obj.year = 999; obj.color = "Color is Value"; context.Response.Write(obj.ToJsJson()); } public bool IsReusable { get { return false; } } } //返回值為 {"color":"Color is Value","make":"Make is Value","model":"Model is Value","year":999} -----------------C#由Json生成對象----------------------- javascript調用測試代碼 代碼如下: $('#postJson').click(function() { var m_obj = { make: "Dodge", model: "Coronet R/T", year: 1968, color: "yellow" }; var jsonStr = JSON.stringify(m_obj); //用Json2.js生成Json字符串 $.ajax({ url: "postJsonHandler.ashx", type: 'POST', data: { postjson: jsonStr }, dataType: 'json', timeout: 1000, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus) }, success: function(result) { alert(result.success); } }); }); C#後台生成代碼 代碼如下: public class postJsonHandler: IHttpHandler { public void ProcessRequest(HttpContext context) { string jsonStr = context.Request["postjson"]; TestObj obj = jsonStr.FromJsonTo<TestObj>(); if (string.IsNullOrEmpty(obj.make) || string.IsNullOrEmpty(obj.model) || string.IsNullOrEmpty(obj.color) || obj.year < 0) { context.Response.Write("{success:false}"); } else { context.Response.Write("{success:true}"); } public bool IsReusable { get { return false; } } } 使用Json時需要注意,服務器端拼湊生成Json字符串時,一定要注意把字符串用""包裹,不然客戶端接收時肯定會報錯,根據Json字符串生成對象,是根據對應的名稱賦值,多於或少於都不會報錯.