实体数据Model
[Serializable] public class UserModel { //public UserModel(string name, string classname, string stunumber) //{ // Uname = name; // ClassName = classname; // StuNumber = stunumber; //} public string Uname=""; public string ClassName=""; public string StuNumber=""; }
生成JSON格式数据(实体转JSON)
[HttpPost] public ActionResult About() { List<UserModel> allList = new List<UserModel>(); //allList.Add(new UserModel("张三", "三年级一班", "stu007")); //allList.Add(new UserModel("李思", "四年级二班", "stu008")); //allList.Add(new UserModel("王五", "五年级九班", "stu002")); //allList.Add(new UserModel("蒋柳", "三年级八班", "stu011")); // var xyz = new { name = "zhangsan", pass = "7720135" }; //return Json(xyz,JsonRequestBehavior.AllowGet); return Json(allList); }
将JSON格式数据转换为实体对象
需要引用:System.Runtime.Serialization.dll 和 System.ServiceModel.Web.dll
public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; string jsstr = "[{\"Uname\":\"张三\",\"ClassName\":\"三年级一班\",\"StuNumber\":\"stu007\"},{\"Uname\":\"李思\",\"ClassName\":\"四年级二班\",\"StuNumber\":\"stu008\"},{\"Uname\":\"王五\",\"ClassName\":\"五年级九班\",\"StuNumber\":\"stu002\"},{\"Uname\":\"蒋柳\",\"ClassName\":\"三年级八班\",\"StuNumber\":\"stu011\"}]"; using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsstr))) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<UserModel>)); List<UserModel> tpAll = (List<UserModel>)serializer.ReadObject(ms); ViewData["Message"] = tpAll.Count; } return View(); }