• ASP.Net MVC中JSON处理。


    实体数据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();
            }
  • 相关阅读:
    Redis 分区
    Redis 管道技术
    8完善博客 8-1 博客主页面开发
    7章 Admin
    6章 Models
    开发第一个Template
    云服务器装teamviewer
    Centos搭建图形界面VNC
    创建应用,并了解应用目录下各文件的作用,同时创建第一个文件响应
    setings.py配置文件详解
  • 原文地址:https://www.cnblogs.com/lidingwen/p/3178194.html
Copyright © 2020-2023  润新知