欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#序列化与反序列化学习笔记

程序员文章站 2023-09-28 23:18:27
本笔记摘抄自:https://www.cnblogs.com/maitian-lf/p/3670570.html,记录一下学习过程以备后续查用。 序列化是把一个内存中的对象的信息转化成一个可以持久化保存的形式,以便于保存或传输。序列化的主要作用是不同平台之间进行通信,常用的序 列化有json、xml ......

    本笔记摘抄自:,记录一下学习过程以备后续查用。

    序列化是把一个内存中的对象的信息转化成一个可以持久化保存的形式,以便于保存或传输。序列化的主要作用是不同平台之间进行通信,常用的序

列化有json、xml、文件等,下面就逐个讲下这三种序列化的方法。

    一、序列化为json

    c#中用于对象和json相互转换的原生类有两个:datacontractjsonserializer和javascriptserializer,其中javascriptserializer主要用于web浏览器和服

务器之间的通信。这里主要讲datacontractjsonserializer的使用,要使用datacontractjsonserializer,先要在项目中引用system.runtime.serialization。

    首先准备一个测试的类book:

    class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        static void main(string[] args)
        {
        }
    }

    [datacontract]指定该类型要定义或实现一个数据协定,并可由序列化程序(如system.runtime.serialization.datacontractserializer)进行序列化。

    [datamember]当应用于类型的成员时,指定该成员是数据协定的一部分并可由system.runtime.serialization.datacontractserializer进行序列化。

    首先创建一个book对象,然后实例化一个datacontractjsonserializer实例,最后用该实例的writeobject()方法将对象写到流中,代码如下:

    class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        static void main(string[] args)
        {
            #region 对象序列化为json
            book book = new book() { id = 101, name = "c#程序设计", price = 79.5f };

            //序列化为json
            datacontractjsonserializer jsonserializer = new datacontractjsonserializer(typeof(book));
            using (memorystream stream = new memorystream())
            {
                jsonserializer.writeobject(stream, book);
                string result = encoding.utf8.getstring(stream.toarray());
                console.writeline(result);
            }
            console.read();
            #endregion
        }
    }

    运行结果如下:

C#序列化与反序列化学习笔记

    将一个json格式的字符串反序列化为对象是用datacontractjsonserializer实例的readobject()方法,代码如下:

    class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        static void main(string[] args)
        {
            #region json反序列化为对象
            book book = new book();
            //json反序列化为对象
            string oristr = "{\"id\":101,\"name\":\"c#程序设计\",\"price\":79.5}";
            datacontractjsonserializer jsonserializer = new datacontractjsonserializer(typeof(book));
            using (memorystream stream = new memorystream(encoding.utf8.getbytes(oristr)))
            {
                book outbook = jsonserializer.readobject(stream) as book;
                console.writeline($"{outbook.id} {outbook.name} {outbook.price}");
            }
            console.read();
            #endregion
        }
    }

    运行结果如下:

C#序列化与反序列化学习笔记

    我们也可以把上面的json序列化与反序列为封装成泛型方法,这样可以公用,全部代码如下:

    class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        public class serializerhelper
        {
            /// 将对象序列化为json文件
            /// </summary>
            /// <typeparam name="t">类型</typeparam>
            /// <param name="t">实例</param>
            /// <param name="path">存放路径</param>
            public static void objecttojson<t>(t t, string path) where t : class
            {
                datacontractjsonserializer formatter = new datacontractjsonserializer(typeof(t));
                using (filestream stream = new filestream(path, filemode.openorcreate))
                {
                    formatter.writeobject(stream, t);
                }
            }

            /// <summary>
            /// 将对象序列化为json字符串
            /// </summary>
            /// <typeparam name="t">类型</typeparam>
            /// <param name="t">实例</param>
            /// <returns>json字符串</returns>
            public static string objecttojson<t>(t t) where t : class
            {
                datacontractjsonserializer formatter = new datacontractjsonserializer(typeof(t));
                using (memorystream stream = new memorystream())
                {
                    formatter.writeobject(stream, t);
                    string result = encoding.utf8.getstring(stream.toarray());
                    return result;
                }
            }

            /// <summary>
            /// 将json字符串反序列化为对象
            /// </summary>
            /// <typeparam name="t">类型</typeparam>
            /// <param name="json">json格式字符串</param>
            /// <returns>对象</returns>
            public static t jsontoobject<t>(string json) where t : class
            {
                datacontractjsonserializer formatter = new datacontractjsonserializer(typeof(t));
                using (memorystream stream = new memorystream(encoding.utf8.getbytes(json)))
                {
                    t result = formatter.readobject(stream) as t;
                    return result;
                }
            }
        }

        static void main(string[] args)
        {
            #region json序列化与反序列化泛型方法
            book book = new book() { id = 101, name = "c#程序设计", price = 79.5f };

            //对象序列化为json
            string result = serializerhelper.objecttojson(book);
            console.writeline(result);

            //json反序列化为对象
            string oristr = "{\"id\":101,\"name\":\"c#程序设计\",\"price\":79.5}";
            book outbook = serializerhelper.jsontoobject<book>(oristr);
            console.writeline($"{outbook.id} {outbook.name} {outbook.price}");

            console.read();
            #endregion
        }
    }

    运行结果如下:

C#序列化与反序列化学习笔记

    二、序列化为xml

    c#中将对象序列化和反序列化为xml的类是xmlserializer,要引用system.xml.serialization。

    首先创建一个xmlserializer对象实例,然后用实例的serialize方法将对象写入到文件流中,代码如下:

    public class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        public class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        static void main(string[] args)
        {
            #region 对象序列化为xml(文件流)
            book book = new book() { id = 101, name = "c#程序设计", price = 79.5f };

            xmlserializer xmlserializer = new xmlserializer(typeof(book));
            using (filestream stream = new filestream(@"e:\book.xml", filemode.openorcreate))
            {
                xmlserializer.serialize(stream, book);
            }
            console.read();
            #endregion
        }
    }

    程序运行后会在c盘产生一个book.xml文件,内容如下:

<?xml version="1.0"?>
<book xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://www.w3.org/2001/xmlschema">
  <id>101</id>
  <name>c#程序设计</name>
  <price>79.5</price>
</book>

    当然也可以将对象转换成对象流,然后转换成xml格式的字符串,代码如下:

    public class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        public class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        static void main(string[] args)
        {
            #region 对象序列化为xml(对象流)
            book book = new book() { id = 101, name = "c#程序设计", price = 79.5f };

            xmlserializer xmlserializer = new xmlserializer(typeof(book));
            using (memorystream stream = new memorystream())
            {
                xmlserializer.serialize(stream, book);
                string result = encoding.utf8.getstring(stream.toarray());  //转换成xml字符串
                console.writeline(result);
            }
            console.read();
            #endregion
        }
    }

    运行结果如下:

C#序列化与反序列化学习笔记

    将xml文件反序列化的方法是用xmlserializer实例的deserialize()方法,代码如下:

    public class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        public class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        static void main(string[] args)
        {
            #region xml文件反序列化为对象
            book book = new book() { id = 101, name = "c#程序设计", price = 79.5f };

            xmlserializer xmlserializer = new xmlserializer(typeof(book));
            using (filestream stream = new filestream(@"e:\book.xml", filemode.openorcreate))
            {
                xmlreader xmlreader = new xmltextreader(stream);
                book outbook = xmlserializer.deserialize(xmlreader) as book;//反序列化
                console.writeline($"{outbook.id} {outbook.name} {outbook.price}");
            }
            console.read();
            #endregion
        }
    }

    运行结果如下:

C#序列化与反序列化学习笔记

    我们同样也可以把上面的xml序列化与反序列为封装成泛型方法,这样可以公用,全部代码如下:

    public class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        public class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        /// <summary>
        /// 序列化反序列化帮助类
        /// </summary>
        public class serializerhelper
        {
            /// <summary>
            /// 将对象序列化为xml文件
            /// </summary>
            /// <typeparam name="t">类型</typeparam>
            /// <param name="t">对象</param>
            /// <param name="path">xml存放路径</param>
            public static void objecttoxml<t>(t t, string path) where t : class
            {
                xmlserializer formatter = new xmlserializer(typeof(t));
                using (filestream stream = new filestream(path, filemode.openorcreate))
                {
                    formatter.serialize(stream, t);
                }
            }

            /// <summary>
            /// 将对象序列化为xml字符串
            /// </summary>
            /// <typeparam name="t">类型</typeparam>
            /// <param name="t">对象</param>
            public static string objecttoxml<t>(t t) where t : class
            {
                xmlserializer formatter = new xmlserializer(typeof(t));
                using (memorystream stream = new memorystream())
                {
                    formatter.serialize(stream, t);
                    string result = encoding.utf8.getstring(stream.toarray());
                    return result;
                }
            }

            /// <summary>
            /// 将xml文件反序列化为对象
            /// </summary>
            /// <typeparam name="t">类型</typeparam>
            /// <param name="t">对象</param>
            /// <param name="path">xml路径</param>
            /// <returns>对象</returns>
            public static t xmltoobject<t>(t t, string path) where t : class
            {
                xmlserializer formatter = new xmlserializer(typeof(t));
                using (filestream stream = new filestream(path, filemode.openorcreate))
                {
                    xmlreader xmlreader = new xmltextreader(stream);
                    t result = formatter.deserialize(xmlreader) as t;
                    return result;
                }
            }
        }

        static void main(string[] args)
        {
            #region xml序列化与反序列化泛型方法
            book book = new book() { id = 101, name = "c#程序设计", price = 79.5f };

            //对象序列化为xml
            serializerhelper.objecttoxml(book, @"e:\book.xml");

            //xml反序列化为对象
            book outbook = serializerhelper.xmltoobject(book, @"e:\book.xml");
            console.writeline($"{outbook.id} {outbook.name} {outbook.price}");

            console.read();
            #endregion
        }
    }

    三、序列化为二进制文件

    c#中将对象序列化和反序列化为二进制文件的类是binaryformatter,要引用system.runtime.serialization.formatters.binary,另外book类头要加

[serializable]属性。

    先创建一个binaryformatter对象实例,然后用实例的serialize的方法将对象写入到文件流中,代码如下:

    public class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        [serializable]
        public class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        static void main(string[] args)
        {
            #region 对象序列化为二进制文件
            book book = new book() { id = 101, name = "c#程序设计", price = 79.5f };

            //对象序列化为二进制文件
            binaryformatter formatter = new binaryformatter();
            using (filestream stream = new filestream(@"e:\book.txt", filemode.openorcreate))
            {
                formatter.serialize(stream, book);
            }
            console.read();
            #endregion
        }
    }

    可以通过binaryformatter类型实例的deserialize()方法把二进制文本反序列化为对象,代码如下:

    public class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        [serializable]
        public class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        static void main(string[] args)
        {
            #region 将二进制文件反序列化为对象
            book book = new book() { id = 101, name = "c#程序设计", price = 79.5f };

            //序列化文件
            binaryformatter formatter = new binaryformatter();
            using (filestream stream = new filestream(@"e:\book.txt", filemode.openorcreate))
            {
                book outbook = formatter.deserialize(stream) as book;
                console.writeline($"{outbook.id} {outbook.name} {outbook.price}");
            }
            console.read();
            #endregion
        }
    }

    运行结果如下:

C#序列化与反序列化学习笔记

    我们同样也可以把序列化和把序列化为二进制文件的方法封装成泛型方法,全部代码如下:

    public class program
    {
        /// <summary>
        /// book类
        /// </summary>
        [datacontract]
        [serializable]
        public class book
        {
            [datamember]
            public int id { get; set; }

            [datamember]
            public string name { get; set; }

            [datamember]
            public float price { get; set; }
        }

        /// <summary>
        /// 序列化反序列化帮助类
        /// </summary>
        public class serializerhelper
        {
            #region 二进制文件序列化反序列化
            /// <summary>
            /// 将对象序列化为字符串
            /// </summary>
            /// <typeparam name="t">类型</typeparam>
            /// <param name="t">实例</param>
            /// <returns>字符串</returns>
            public static string objecttostring<t>(t t)
            {
                binaryformatter formatter = new binaryformatter();
                using (memorystream stream = new memorystream())
                {
                    formatter.serialize(stream, t);
                    string result = encoding.utf8.getstring(stream.toarray());
                    return result;
                }
            }

            /// <summary>
            /// 将对象序列化为二进制文件
            /// </summary>
            /// <typeparam name="t">类型</typeparam>
            /// <param name="t">实例</param>
            /// <param name="path">存放路径</param>
            public static void objecttobinaryfile<t>(t t, string path)
            {
                binaryformatter formatter = new binaryformatter();
                using (filestream stream = new filestream(path, filemode.openorcreate))
                {
                    formatter.serialize(stream, t);
                    stream.flush();
                }
            }

            /// <summary>
            /// 将字符串反序列为对象
            /// </summary>
            /// <typeparam name="t">类型</typeparam>
            /// <param name="s">字符串</param>
            /// <returns>对象</returns>
            public static t stringtoobject<t>(string s) where t : class
            {
                byte[] buffer = encoding.utf8.getbytes(s);
                binaryformatter formatter = new binaryformatter();
                using (memorystream stream = new memorystream(buffer))
                {
                    t result = formatter.deserialize(stream) as t;
                    return result;
                }
            }

            /// <summary>
            /// 将二进制文件反序列化为对象
            /// </summary>
            /// <typeparam name="t">类型</typeparam>
            /// <param name="path">路径</param>
            /// <returns>对象</returns>
            public static t binaryfiletoobject<t>(string path) where t : class
            {
                using (filestream stream = new filestream(path, filemode.open))
                {
                    binaryformatter formatter = new binaryformatter();
                    t result = formatter.deserialize(stream) as t;
                    return result;
                }
            }
            #endregion
        }

        static void main(string[] args)
        {
            #region 二进制文件序列化反序列化泛型方法
            book book = new book() { id = 101, name = "c#程序设计", price = 79.5f };
            //对象序列化为二进制文件
            serializerhelper.objecttobinaryfile(book, @"e:\book.txt");

            //二进制文件反序列化为对象
            book outbook = serializerhelper.binaryfiletoobject<book>(@"e:\book.txt") as book;
            console.writeline($"{outbook.id} {outbook.name} {outbook.price}");

            console.read();
            #endregion
        }
    }

    运行结果如下:

C#序列化与反序列化学习笔记