Json
* C#中json
- 需要用NuGet添加Newtonsoft.Json
1、使用JsonConvert,需要引入using Newtonsoft.Json;
1.1、直接传JSON对象:
后台:
var book = new BookInfo { BookId = 1, Title = "C#", Author = "DD" }; return Json(book);
前台:不可以直接html(result)
$.post('DB/JsonTest', function (result) { var z = result.Title; //直接取值 $("#result").html(z); });
1.2、传JSON字符串:
后台:
var book = new BookInfo { BookId = 1, Title = "C#", Author = "DD" }; //将对象系列化为json字符串 //{"BookId":1,"Title":"C#","Author":"DD","Publish":null,"PublishDate":"0001-01-01T00:00:00","Price":0.0} var k1 = JsonConvert.SerializeObject(book); //还原成为book,将json字符串反序列化为对象 var k2 = JsonConvert.DeserializeObject<BookInfo>(k1); return Json(k1);
前台:取值时要eval()或者JSON.parse(),可以直接html(result),原因是返回的是json字符串格式
$.post('DB/JsonTest', function (result) { var c = JSON.parse(result); var a = c.Title; $("#result").html(result); });
1.3、传字符串 :
后台:
[HttpGet] public string kk() { //在控制器里面拼接页面元素,不能写 @Html.Raw() 等之类的 return "<Label>dkdjkjdkjfkdfj</Label><br/>"; }
前台:
$.get('DB/kk', function (result) { $("#result").html(result); })
1.4 传DataTable的Demo
[HttpPost] public ActionResult Cache1() { DataTable dt = SqlHelper.ExecuteDataTable("select * from bookinfo", null); //系列化为json字符串,[{第一行数据}, {...}, {最后一行数据}] return Json(JsonConvert.SerializeObject(dt)); }
function JsonTest2() { $.ajax({ type: 'post', url: '@Url.Action("Cache1")', success: function (result) { var res = JSON.parse(result); //解析字符串为json对象 var content = "<table>"; for (var i = 0; i < res.length; i++) { //循环取值 content += "<tr><td>" + res[i].BookId + "</td><td>" + res[i].Author + "</td></tr>"; } content += "</table>"; $("#showResult").html(content); } }); }
2、返回JSON格式数据方式
- return Json(object, JsonRequestBehavior.AllowGet); 第一个参数只要是object对象即可
- 返回
return new JsonResult() { Data = book, MaxJsonLength = int.MaxValue, ContentType = "application/json" };
3、dynamic
string json = "{\"id\":1, \"name\":\"xx\", \"age\":1}"; //这里直接使用dynamic,不用再创建一个对象去接受 var obj = JsonConvert.DeserializeObject<dynamic>(json); var k1 = obj.name;
* js中json
var s = {"status":200, "msg":"ok", "data":{"id":1, "name":"xp"}}; //对象 var k = JSON.stringify(s); //json字符串 var k1 = JSON.parse(k); //json对象 var s2 = '{"status":200, "msg":"ok", "data":{"id":1, "name":"xp"}}'; //json字符串 //json字符串转换为json对象 JSON.parse(s2); eval("("+s2+")");