.Net序列化与反序列化的2种方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;    //方法一的引用
using System.Web.Script.Serialization;   //方法二的引用

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            #region(一)引用Newtonsoft.Json
            //①序列化实体对象
            User u = new User()
            {
                Name = "曹操",
                Age = 10,
                Sex = ""
            };
            string json = JsonConvert.SerializeObject(u);
            Console.WriteLine(json);   
            //{"Name":"曹操","Age":10,"Sex":"男"}
            Console.ReadKey();

            //②反序列化实体对象
            User model = JsonConvert.DeserializeObject<User>(json);
            Console.WriteLine(string.Format("姓名:{0},年龄:{1},性别:{2}",model.Name,model.Age,model.Sex));   
            //姓名:曹操,年龄:10,性别:男
            Console.ReadKey();

            //③序列化实体对象集合
            List<User> ulst = new List<User>()
            {
                new User {Name="曹操",Age=10,Sex="" },
                new User {Name="刘备",Age=12,Sex="" },
                new User {Name="孙权",Age=13,Sex="" },
            };
            string json2 = JsonConvert.SerializeObject(ulst);
            Console.WriteLine(json2);    
            //[{"Name":"曹操","Age":10,"Sex":"男"},{"Name":"刘备","Age":12,"Sex":"女"},{"Name":"孙权","Age":13,"Sex":"男"}]
            Console.ReadKey();


            //④反序列化实体对象集合
            List<User> ulst2 = JsonConvert.DeserializeObject<List<User>>(json2);
            foreach (User user in ulst2)
            {
                Console.WriteLine(string.Format("姓名:{0},年龄:{1},性别:{2}", user.Name, user.Age, user.Sex));
            }
            //姓名:曹操,年龄:10,性别:男
            //姓名:刘备,年龄:12,性别:女
            //姓名:孙权,年龄:13,性别:男
            Console.ReadKey();

            #endregion

            #region(二)引用System.Web.Extensions
            //①序列化实体对象
            User u2 = new User()
            {
                Name = "曹操",
                Age = 10,
                Sex = ""
            };
            JavaScriptSerializer js = new JavaScriptSerializer();
            string json3 = js.Serialize(u2);
            Console.WriteLine(json3);
            //{"Name":"曹操","Age":10,"Sex":"男"}
            Console.ReadKey();

            //②反序列化实体对象
            User model2 = js.Deserialize<User>(json3);
            Console.WriteLine(string.Format("姓名:{0},年龄:{1},性别:{2}", model2.Name, model2.Age, model2.Sex));
            //姓名:曹操,年龄:10,性别:男
            Console.ReadKey();
            #endregion


        }
    }
    //User实体对象
    class User
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
    }
}

 

posted @ 2018-05-16 17:03  yanyufei  阅读(381)  评论(0编辑  收藏  举报