1.前臺將Json字符串數據傳遞到後臺進行處理javascript
//var Json = '{"User":[{"UserName":"a","PassWord":"a"},{"UserName":"b","PassWord":"b"}]}';這是前臺 string json = Request.Form["Json"]; JObject o = (JObject)JsonConvert.DeserializeObject(json); JToken arr = (JToken)o["User"];//此地返回的是多條記錄,因此要遍歷 foreach (var token in arr) { Person p = JsonConvert.DeserializeObject<Person>(token.ToString()); //在此對p進行增刪改操做,p已是一個實體類的實例 } Response.End();
對Json字符串進行後臺處理,須要應用到程序集Newtonsoft.Json.dlljava
另外:若是是一條記錄的Json,處理方式是:json
//var Json = '{"UserName":"c","PassWord":"c"}';這是前臺 string json = Request.Form["Json"]; JObject o = (JObject)JsonConvert.DeserializeObject(json); JToken arr = (JToken)o;//此地返回的是一條記錄,不進行選項選擇都是一條,不用遍歷 Person p = JsonConvert.DeserializeObject<Person>(arr.ToString()); //在此對p進行增刪改操做,p已是一個實體類的實例 Response.End();
2.組織對象,而後轉換爲Json字符串post
var opts = { UserName: "d", PassWord:"d" }; var json = jsonParseString(opts);
方法jsonParseString 代碼以下code
//JSON對象轉字符串 function jsonParseString(o) { try { if (o == undefined) { return ""; } var r = []; if (typeof o == "string") return "\"" + o.replace(/([\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\""; if (typeof o == "object") { if (!o.sort) { for (var i in o) r.push("\"" + i + "\":" + jsonParseString(o[i])); if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) { r.push("toString:" + o.toString.toString()); } r = "{" + r.join() + "}" } else { for (var l = 0; l < o.length; l++) r.push(jsonParseString(o[l])) r = "[" + r.join() + "]"; } return r; } return o.toString().replace(/\"\:/g, '":""'); } catch (e) { return e.Message; } }
最終生成的json字符串爲:var Json = '{"UserName":"d","PassWord":"d"}',知足傳遞到後臺的需求orm
3.前臺直接傳遞到本身的後臺,添加Response.End();能夠防止傳遞HTML到前臺對象
4.後臺將數據轉換爲Json傳遞到前臺blog
這是後臺代碼:token
protected void Page_Load(object sender, EventArgs e) { if (Request.Form["Type"] == "GetJson") { Person p = new Person(); p.UserName = "e"; p.PassWord = "e"; string json = JsonConvert.SerializeObject(p);//此處將對象轉換爲Json了 Response.Write(json); Response.End(); } }
注意還能夠將對象集合轉換爲Json,實例代碼:ip
List<Person> persons = new List<Person>(); Person p = new Person(); p.UserName = "f"; p.PassWord = "f"; persons.Add(p); persons.Add(p); string json = JsonConvert.SerializeObject(persons);//此處將對象轉換爲Json了 內容爲 "[{\"UserName\":\"f\",\"PassWord\":\"f\"},{\"UserName\":\"f\",\"PassWord\":\"f\"}]" Response.Write(json); Response.End();
同時他還能夠將DataTable轉換爲Json字符串,實例代碼以下:
protected void Page_Load(object sender, EventArgs e) { if (Request.Form["Type"] == "GetJson") { DataTable dt = ZXGA.Utility.DbHelperOleDb.Query(App_Init.ConnStr(),"select * from jjdwb").Tables[0]; string json = JsonConvert.SerializeObject(dt); Response.Write(json); Response.End(); } }
下面是前臺代碼:
$.post("test2.aspx", { Type: "GetJson" }, function (data) { //var obj = $.parseJSON(data);//方法一 var obj = eval('(' + data + ')'); //方法二 alert(obj.UserName); });