zoukankan      html  css  js  c++  java
  • C# 序列化(Serialize)与反序列化(Deserialize)

    序列化是将对象的状态信息转换为可保持或传输的格式的过程(一堆字符),比如转化为二进制、xml、json等的过程。

    反序列化就是将在序列化过程中所生成的二进制串、xml、json等转换成数据结构或者对象的过程。

    这两个过程结合起来,可以轻松地存储、传输数据。

    最主要的作用有:

    • 在进程下次启动时读取上次保存的对象的信息
    • 在不同的AppDomain或进程之间传递数据
    • 在分布式应用系统中传递数据序列化,其实就是将对象的状态信息转换为可以存储或传输的数据形式

    比如有这样一个类
    class User{
    public string UserName;
    public string Password;
    }
    我们可以把它的实例转换为这样的xml
    <User>
    <UserName>value</UserName>
    <Password>value</Password>
    </User>
    可以认为这样就是序列化。

    XML序列化和反序列化

    对象序列化之后的结果是XML形式的,通过XmlSerializer 类来实现的,这个类位于System.Xml.Serialization命名空间下。XML序列化不能序列化私有数据。

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Xml.Serialization;
    
    namespace ConsoleApplication1
    {
        public class Person
        {
            public string Name;//姓名
            public bool Sex;//性别,是否是男
            public Person() { }//必须提供无参构造器,否则XmlSerializer将出错
            public Person(string name, bool sex)
            {
                this.Name = name;
                this.Sex = sex;
            }
    
            public override string ToString()
            {
                return "姓名:" + this.Name + "	性别:" + (this.Sex ? "" : "");
            }
        }
    
        public class Programmer : Person
        {
    
            public string Language;//编程语言
            public Programmer() { }//必须提供无参构造器,否则XmlSerializer将出错
            public Programmer(string name, bool sex, string language)
                : base(name, sex)//base关键字用于从派生类中访问基类成员
            {
                this.Language = language;
            }
    
            public override string ToString()
            {
                return base.ToString() + "	编程语言:" + this.Language;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                //创建Programmer列表,并添加对象
                List<Programmer> list = new List<Programmer>();
                list.Add(new Programmer("李志伟", true, "C#"));
                list.Add(new Programmer("Coder2", false, "C++"));
                list.Add(new Programmer("Coder3", true, "Java"));
                //System.Reflection.PropertyInfo[] properties = list.GetType().GetProperties();//反射获取对象的属性
                //使用XML序列化对象
                string fileName = @"C:Userschris_guDesktopProgrammers.xml";//文件名称与路径
                Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
                XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>), new Type[] { typeof(Programmer), typeof(Person) });//创建XML序列化器,需要指定对象的类型
                xmlFormat.Serialize(fStream, list);
    
                //使用XML反序列化对象
    
                fStream.Position = 0;//重置流位置
                list.Clear();
                list = (List<Programmer>)xmlFormat.Deserialize(fStream);
                foreach (Programmer p in list)
                {
                    Console.WriteLine(p);
                }
                Console.Read();
            }
        }
    }

    Json序列化

    第一种:使用JavaScriptSerializer类,适用Web平台

    C#将对象序列化成JSON字符串

    using System.Web.Script;
    using System.Web.Script.Serialization;
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                foreach (DataRow dr in dt.Rows)
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("Dev_NO", dr["Dev_NO"].ToString());
                    data.Add("Dev_Name", dr["Dev_Name"].ToString());
                    data.Add("Ol_Phone", dr["Ol_Phone"].ToString());
                    data.Add("Ol_IP", dr["Ol_IP"].ToString());
                    data.Add("Ol_Status", dr["Ol_Status"].ToString());
                    list.Add(data);
                }
                Response.Write(serializer.Serialize(list));

    输出结果为:

    [{"Dev_NO":"00066666","Dev_Name":"test","Ol_Phone":"13766668888","Ol_IP":"10.196.209.174","Ol_Status":"2"},{"Dev_NO":"000F0000","Dev_Name":"test_hzlkhq","Ol_Phone":"13066668888","Ol_IP":"192.168.1.198","Ol_Status":"2"}]

    如何将Json字符串转换成对象使用呢?

        public class Model  
            {  
                public string Dev_NO { get; set; }  
                public string Dev_Name { get; set; }  
                public string Ol_Phone { get; set; }  
                public string Ol_IP { get; set; }  
                public int Ol_Status { get; set; }  
            }  
        string requestMes="[{"Dev_NO":"00066666","Dev_Name":"test","Ol_Phone":"13766668888","Ol_IP":"10.196.209.174","Ol_Status":"2"},{"Dev_NO":"000F0000","Dev_Name":"test_hzlkhq","Ol_Phone":"13066668888","Ol_IP":"192.168.1.198","Ol_Status":"2"}]";  
        JavaScriptSerializer serializer = new JavaScriptSerializer();  
        var Json = serializer.Deserialize<List<Model>>(requestMes);  

    第二种使用DataContractJsonSerializer,适用通用平台

    using System.Runtime.Serialization.Json;  
    using System.Runtime.Serialization;
    public class Model  
        {  
            public string Dev_NO { get; set; }  
            public string Dev_Name { get; set; }  
            public string Ol_Phone { get; set; }  
            public string Ol_IP { get; set; }  
            public int Ol_Status { get; set; }  
        } 
    
        public class Test  
        {  
            public static DataTable getData()  
            {  
                var a = "{"Dev_NO":"00066666","Dev_Name":"test","Ol_Phone":"13766668888","Ol_IP":"10.196.209.174","Ol_Status":"2"}";  
                var serializer = new DataContractJsonSerializer(typeof(List<DTUModel>));  
                var mStream = new MemoryStream(Encoding.UTF8.GetBytes(a.ToString()));  
                List<DTUModel> list = (List<DTUModel>)serializer.ReadObject(mStream);  
                DataTable dt = new DataTable();  
                return dt;  
            }  
        }  
  • 相关阅读:
    【js】字符串反转可实现的几种方式
    【js】深拷贝一文中的几个错误点
    关于js浅拷贝与深拷贝的理解
    chrome内核浏览器插件的使用--Tampermonkey(油猴插件)
    react复习总结(2)--react生命周期和组件通信
    react复习总结(1)--react组件开发基础
    对gulp的理解和使用(一)
    [luogu3391][文艺平衡树]
    [Splay][学习笔记]
    [bzoj1116][POI2008][CLO]
  • 原文地址:https://www.cnblogs.com/chrisghb8812/p/5590980.html
Copyright © 2011-2022 走看看