首页 > 学院 > 开发设计 > 正文

Josn转换

2019-11-14 16:11:01
字体:
来源:转载
供稿:网友

也是搬的,大家勿喷,贴出来只为了自己记忆查找

需要引用

System.Web.Extensions.dll 这个类库

命名空间:

System.Web.Script.Serialization

数据结构

public class Team
    {
        public string Name { get; set; }
        public List<User> Users { get; set; }
    } 
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

 Class --> JSON

javaScriptSerializer js = new JavascriptSerializer();
            Team team = new Team()
            {
                Name = "梦之队",
                Users = new List<User>() { 
                 new User() { Id = 1, Name = "XXX" },
                  new User() { Id = 2, Name = "YYY" },
                   new User() { Id = 3, Name = "ZZZ" },
                }
            };
            string json = js.Serialize(team);
            Console.WriteLine(json);

 

Json --> Class

            string json = "{/"Name/":/"梦之队/",/"Users/":[{/"Id/":1,/"Name/":/"XXX/"},{/"Id/":2,/"Name/":/"YYY/"},{/"Id/":3,/"Name/":/"ZZZ/"}]}";
            JavaScriptSerializer js = new JavaScriptSerializer();
            Team team = js.Deserialize<Team>(json);

 

前台可以把一个数组转换成Json

需要引用json.js

 $.toJSON(data);

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表