zoukankan      html  css  js  c++  java
  • 20150317--序列化,反序列化(2)

    序列化,反序列化除了转二进制之外还有另外一种序列化的方法:Soap序列化。

    创建一个类,同样不要忘记序列化标记 [Serializable]

    [Serializable]
    
    public class StudentData
    {
       public StudentData()
       {
       }
    
        private string _Code;
    
        public string Code
        {
            get { return _Code; }
            set { _Code = value; }
        }
        private string _Name;
    
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
        private string _Nation;
    
        public string Nation
        {
            get { return _Nation; }
            set { _Nation = value; }
        }
    }

    在cs中的需要添加引用:

    using System.IO;//流

    using System.Runtime.Serialization.Formatters.Soap;//Soap类,

    Soap类需要先在项目上添加引用,右键--添加引用 到 引用管理器界面,搜索soap,选中并确定:

    image
    序列化与反序列化按钮的代码(请注意文中加粗部分,这里是与二进制序列化的主要区别):

    //序列化按钮
        protected void Button1_Click(object sender, EventArgs e)
        {
            stuDA ss = new stuDA
            {
                Code = TextBox1.Text,
                Name = TextBox2.Text,
                Nation = TextBox3.Text
            };
            FileStream fs = null;
            try
            {
                string path = Server.MapPath("data/bbb.txt");//映射服务器端的硬盘物理路径
                fs = new FileStream(path, FileMode.Create);//建立文件流
                SoapFormatter bf = new SoapFormatter();//soap格式化器
                bf.Serialize(fs, ss);//把对象序列化
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();//流使用后必须关闭。
                }
            }
        }
        //反序列化
        protected void Button2_Click(object sender, EventArgs e)
        {
            string path = Server.MapPath("data/bbb.txt");
            FileStream fs = null;
            try
            {
                fs = new FileStream(path, FileMode.Open);//使用流打开文件
    
                SoapFormatter by = new SoapFormatter();//soap转化器
    
                stuDA sdata = (stuDA)by.Deserialize(fs);//反序列化成对象
                Label1.Text = sdata.Code;
                Label2.Text = sdata.Name;
                Label3.Text = sdata.Nation;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }

    在文本框中输入文字:

    image

    序列化结果:

    image

    这里可以很直观的看到对象中变量存储的文字信息。

    反序列化:

    image

    小结:二进制的序列化与Soap的序列化不可混用,用二进制方法进行的序列化,反序列化就必须用二进制的方法进行反序列化。此外,序列化可以放入SQL中,使用二进制序列化的流可以存放在SQL的img类型的列中。

  • 相关阅读:
    java使用 poi导出Excel 2003异常
    ajax 提交复选框
    基于tensorflow的躲避障碍物的ai训练
    现代企业的人力资源困局
    黑暗圣经---物业公司CTO/CEO改如何给老板推荐物业信息化产品
    物业管理系统选择之困——天下有没有白吃的午餐
    江湖风云再起——全球最高性价比私有云平台解决方案发布
    ES6 promise的使用
    C# web API的初步使用!!
    post 与get的区别
  • 原文地址:https://www.cnblogs.com/Tirisfal/p/4343546.html
Copyright © 2011-2022 走看看