序列化 | 反序列化 | Json xml 二进制序列化

来源:互联网 发布:广西柳州网络推广优化 编辑:程序博客网 时间:2024/06/04 18:53

《项目一: 序列化》

创建一个控制台应用程序,命名为“序列化”

using System;using System.Collections.Generic;using System.Configuration;using System.Data.SqlClient;using System.IO;using System.Linq;using System.Runtime.Serialization.Formatters.Binary;using System.Text;using System.Threading.Tasks;using System.Web.Script.Serialization;using System.Xml.Serialization;namespace 序列化{    [Serializable]    public class Person : Animal    {        [NonSerialized]        private string _name;        public string Name         {            get{                 return _name;            }            set            {                _name=value;            }        }        public int Age { get; set; }        public string Email { get; set; }        public Car BenChi { get; set; }        public void Say()        {            Console.WriteLine("OK");        }         }    [Serializable]    public class Animal    {        public void Eat()        {            Console.WriteLine("吃东西");        }    }    [Serializable]    public class Car //汽车    {    }    class Program    {        static void Main(string[] args)        {            //Json序列化 (即:把一个对象转换成一个json格式的字符串)            Person p1 = new Person() { Name = "杨中科", Age = 19, Email = "123@qq.com" };            JavaScriptSerializer jss = new JavaScriptSerializer();            string jsonStr = jss.Serialize(p1);            Console.WriteLine(jsonStr);            //XML序列化 (即:把一个对象转换成一个XML文件的过程)            XmlSerializer xml = new XmlSerializer(typeof(Person));            using (FileStream fs = new FileStream("person.xml", FileMode.OpenOrCreate))            {                xml.Serialize(fs, p1);            }            Console.WriteLine("OK");            //二进制序列化  (即:把一个对象转换成流stream的过程,而流就是一个byte数组)            //将Person对象序列化后保存到磁盘上能,就要操作磁盘文件,所以需要使用文件流(FileStream)            //二进制序列化注意点:            //1.被序列化对象的类型必须标记为"可序列化",即在类前面写上[Serializable](上面的json,xml序列化就不需要标记)            //2.被序列化的类的所有父类也必须被标记为“可序列化” (object类是所有类的基类,object类是被标记为“可序列化”的)            //3.要求被序列化的对象的类型中的所有字段的类型也必须标记为“可序列化”的            //4.如果要求被序列化的对象的类型中的某个字段(属性) 不想被序列化,那么只要在它前面添加一个[NonSerialized],就可以了。但是前提是这个属性不能为自动属性。            //二进制序列化步骤:            //1.创建序列化器:            BinaryFormatter bf = new BinaryFormatter();            //1.1 创建一个文件流            using (FileStream fsWrite = new FileStream("D:/wowo.txt", FileMode.OpenOrCreate))            {                //2.开始执行序列化                bf.Serialize(fsWrite, p1);            }            Console.WriteLine("OK:二进制序列化成功");            Console.ReadKey();        }    }}

list 转换成xml

                   XmlSerializer xml = new XmlSerializer(typeof(List<UserInfo>),"abc");//第二个参数:用于所有 XML 元素的默认命名空间(可选)                    using (FileStream fs = new FileStream(@"d:/abcd.xml", FileMode.Create))                    {                                                xml.Serialize(fs, list);                    }


《项目二:反序列化》

创建一个控制台应用程序,命名为“反序列化”,然后再添加引用,将上面的那个项目(序列化的那个控制台),引入到当前项目(反序列化的这个控制台)中来

using ConsoleApplication1;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.Serialization.Formatters.Binary;using System.Text;using System.Threading.Tasks;namespace 反序列化{    public     class Program    {        static void Main(string[] args)        {            //创建序列化器            BinaryFormatter bf = new BinaryFormatter();            //二进制反序列化的时候注意:            //1.必须获取被序列化的对象的类型所在的程序集(这时候就需要引入对象序列化的时候坐在的程序集),因为:反序列要根据序列化文件重新还原该对象,而序列化文件中只包含那些数据信息,并没有包含该对象的类型的其他相关信息,比如:该对象是继承自哪个父类,实现了哪些接口,类型中包含哪些方法....等等,这些信息在对象序列化文件中都不包含,要获取这些信息就必须通过该类型的程序集来获取。            //2.所以你要对二进制文件反序列化的时候,对方必须把你要反序列化的二进制文件在序列化的时候所在的程序集拷贝给你,然后你引用这个程序集(或者你在同程序集下面进行序列化和反序列化)            using(FileStream fsRead=new FileStream("D:/wowo.txt",FileMode.Open))            {               object obj=  bf.Deserialize(fsRead);               Person p1 = obj as Person;               Console.WriteLine(p1.Age);               Console.WriteLine(p1.Email);               Console.WriteLine(p1.Name);               Console.ReadKey();            }        }    }}


将一个流转换成一个字符串

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace ClientAspApi{    using ClientAspApi.Models;    using System.IO;    using System.Net;    public partial class WebForm1 : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            //1.0使用C#代码模拟浏览器进行URL的请求得到响应数据            WebRequest request = WebRequest.Create("http://localhost:59869/api/Menus/GetMeun");            request.Method = "Get";            //2.0将请求报文发送给服务器,同时拿到服务器的响应报文            WebResponse response = request.GetResponse();            //3.0提取服务器响应报文中的数据(服务端返回的数据是以流的形式返回的)            System.IO.Stream stream = response.GetResponseStream();            //3.1将服务端返回的数据流转换成一个字符串            string responseTxt = string.Empty;            using (StreamReader sr = new StreamReader(stream))            {                responseTxt = sr.ReadToEnd();            }            List<MenuInfo> obj = Jil.JSON.Deserialize<List<MenuInfo>>(responseTxt);            GridView1.DataSource = obj;            GridView1.DataBind();        }    }}





0 0
原创粉丝点击