q我吧

Newtonsoft.Json序列化和反序列

1,序列化
方法:SerializeObject

返回结果是字符串,支持多线程,异步

方法有7个重载

2,反序列化方法

DeserializeObject

支持 泛型、异步、多线程

 

看一下效果:

 

//泛型
public static T DeserializeObject<T>(string value);
//异步
public static Task<object> DeserializeObjectAsync(string value);

 

下面简写几个例子,供参考

序列化:

            var user = new User { Password = "123456", UserName = "TEST" };
            //转换为json字符串
            var resultStr = JsonConvert.SerializeObject(user);
            Console.WriteLine(resultStr);

反序列化:

            //转换成对象
            var user1 = JsonConvert.DeserializeObject<User>(resultStr);
            Console.WriteLine(user1.ToString());

 

集合也一样:

            //复杂一点的
            var role = new Role { Name = "角色名" };
            role.UserList = new List<User>();
            role.UserList.Add(user);
            role.UserList.Add(user1);

            var roleStr = JsonConvert.SerializeObject(role);
            Console.WriteLine(roleStr);

            var role1 = JsonConvert.DeserializeObject<Role>(roleStr);
            Console.WriteLine(role1.ToString());


            //集合
            var userlist = JsonConvert.SerializeObject(role.UserList);
            Console.WriteLine(userlist);
            var userList = JsonConvert.DeserializeObject<List<User>>(userlist);
            Console.WriteLine(userList.ToString());

 

 简单demo下载

 

posted @ 2015-03-23 16:26  渲起浪花  阅读(742)  评论(0编辑  收藏  举报