C#面向对象20 序列化和反序列化

  序列化和反序列化

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

 

  一、序列化为json

  C#中用于对象和json相互转换的原生类有两个:DataContractJsonSerializer和JavaScriptSerializer,其中JavaScriptSerializer主要用于web的浏览器和服务器之间的通信。这里主要讲DataContractJsonSerializer的使用,要使用DataContractJsonSerializer,先要在项目中引用System.Runtime.Serialization。

 

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

[DataContract]
    class Book
    {
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public float Price { get; set; }
    }
[DataContract]指定该类型要定义或实现一个数据协定,并可由序列化程序(如 System.Runtime.Serialization.DataContractSerializer)进行序列化。
[DataMember]当应用于类型的成员时,指定该成员是数据协定的一部分并可由 System.Runtime.Serialization.DataContractSerializer进行序列化。


然后先创建一个Book对象,实例化一个DataContractJsonSerializer实例,最后用该实例的WriteObject()方法将对象写到流中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;

namespace 序列化Json
{
    class Program
    {
        static void Main(string[] args)
        {
            
            Book book = new Book() { ID = 101, Name = "C#程序设计", Price = 79.5f };
            //序列化json
            DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(Book));
             using (MemoryStream stream = new MemoryStream())
             {
                 formatter.WriteObject(stream, book);
                 string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());                 
                 Console.WriteLine(result);
             }
            
            
          
            Console.ReadKey();
        }
    }
    
    [DataContract]
    class Book
    {
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public float Price { get; set; }
    }
}

将一个json格式的字符串反序列化为对象是用DataContractJsonSerializer实例的ReadObject()方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;

namespace 序列化Json
{
    class Program
    {
        static void Main(string[] args)
        {

            //反序列化json
            string oriStr = "{\"ID\":101,\"Name\":\"C#程序设计\",\"Price\":79.5}";
            DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(Book));
            using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(oriStr)))
            {
                Book outBook = formatter.ReadObject(stream) as Book;
                Console.WriteLine(outBook.ID);
                Console.WriteLine(outBook.Name);
                Console.WriteLine(outBook.Price);
            }
            Console.ReadKey();
        }
    }
    
    [DataContract]
    class Book
    {
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public float Price { get; set; }
    }
}

把上面的json序列化与反序列为封装成泛型方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;

namespace 序列化Json
{
    class Program
    {
        static void Main(string[] args)
        {

            Book book = new Book() { ID = 101, Name = "C#程序设计", Price = 79.5f };

            //序列化json
            string result = Serializer.ObjectToJson<Book>(book);
            Console.WriteLine(result);

            //反序列化json
            string oriStr = "{\"ID\":101,\"Name\":\"C#程序设计\",\"Price\":79.5}";
            Book outBook = Serializer.JsonToObject<Book>(oriStr);
            Console.WriteLine(outBook.ID);
            Console.WriteLine(outBook.Name);
            Console.WriteLine(outBook.Price);

            Console.ReadKey();
        }
    }

    public class Serializer
    {
        /// 将对象序列化为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 = System.Text.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(Book));
            using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
            {
                T result = formatter.ReadObject(stream) as T;
                return result;
            }
        }
    } 
    
    [DataContract]
    class Book
    {
        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public float Price { get; set; }
    }
}

 

  二、序列化为xml

C#中将对象序列化和反序列化为xml的类是XmlSerializer,要引用System.Xml.Serialization
先创建一个XmlSerializer对象实例,然后用实例的Serialize的方法将对象写入到文件流中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;

namespace 序列化XML
{
    class Program
    {
        static void Main(string[] args)
        {
            Book book = new Book() { ID = 101, Name = "C#程序设计", Price = 79.5f };

            XmlSerializer formatter = new XmlSerializer(typeof(Book));
            using (FileStream stream = new FileStream(@"c:\book.xml", FileMode.OpenOrCreate))
            {
                formatter.Serialize(stream, book);
            }
            Console.Read();

        }
    }

  
    [Serializable]
    public class Book
    {
       
        public int ID { get; set; }
        public string Name { get; set; }
        public float Price { get; set; }
    }
    
}

  book.xml:

当然也可以将对象转换成对象流,然后转换成xml格式的字符串
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;

namespace 序列化XML
{
    class Program
    {
        static void Main(string[] args)
        {

            Book book = new Book() { ID = 101, Name = "C#程序设计", Price = 79.5f };

            XmlSerializer formatter = new XmlSerializer(typeof(Book));
            using (MemoryStream stream = new MemoryStream())
            {
                formatter.Serialize(stream, book);
                string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());//转换成xml字符串
                Console.WriteLine(result);
            }

            Console.Read();

        }
    }

  
    [Serializable]
    public class Book
    {
       
        public int ID { get; set; }
        public string Name { get; set; }
        public float Price { get; set; }
    }
    
}
将xml文件反序列化的方法是用XmlSerializer实例的Deserialize()方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace 序列化XML
{
    class Program
    {
        static void Main(string[] args)
        {

            XmlSerializer formatter = new XmlSerializer(typeof(Book));
            using (FileStream stream = new FileStream(@"c:\book.xml", FileMode.OpenOrCreate))
            {
                XmlReader xmlReader = new XmlTextReader(stream);
                Book outBook = formatter.Deserialize(xmlReader) as Book;//反序列化
                Console.WriteLine(outBook.ID);
                Console.WriteLine(outBook.Name);
                Console.WriteLine(outBook.Price);
            }

            Console.Read();

        }
    }

  
    [Serializable]
    public class Book
    {
       
        public int ID { get; set; }
        public string Name { get; set; }
        public float Price { get; set; }
    }
    
}
xml序列化与反序列为封装成泛型方法
class Program
     {
         static void Main(string[] args)
         {
             Book book = new Book() { ID = 101, Name = "C#程序设计", Price = 79.5f };
             
             //序列化xml
             Serializer.ObjectToXml(book, @"c:\book.xml");
 
             //反序列化xml
             Book outBook = Serializer.XmlToObject(book, @"c:\book.xml");
             Console.WriteLine(outBook.ID);
             Console.WriteLine(outBook.Name);
             Console.WriteLine(outBook.Price);
             Console.Read();
         }
     }
 
     public class Serializer
     {     
         /// <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 = System.Text.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;
             }
         }       
     }

 

  三、序列化为文件

C#中将对象序列化和反序列化为二进制文件的类是BinaryFormatter,要引用System.Runtime.Serialization.Formatters.Binary
先创建一个BinaryFormatter对象实例,然后用实例的Serialize的方法将对象写入到文件流中
class Program
     {
         static void Main(string[] args)
         {
             Book book = new Book() { ID = 101, Name = "C#程序设计", Price = 79.5f };
 
             //序列化文件
             BinaryFormatter formatter = new BinaryFormatter();
             using (FileStream stream = new FileStream(@"c:\book.txt", FileMode.OpenOrCreate))
             {
                 formatter.Serialize(stream, book);
             }
             Console.Read();
         }
     }
可以通过BinaryFormatter类型实例的Deserialize()方法把二进制文本反序列化为对象
class Program
     {
         static void Main(string[] args)
         {
             Book book = new Book() { ID = 101, Name = "C#程序设计", Price = 79.5f };
 
             //序列化文件
             BinaryFormatter formatter = new BinaryFormatter();
             using (FileStream stream = new FileStream(@"c:\book.txt", FileMode.OpenOrCreate))
             {
                 Book outBook = formatter.Deserialize(stream) as Book;
                 Console.WriteLine(outBook.ID);
                 Console.WriteLine(outBook.Name);
                 Console.WriteLine(outBook.Price);
             }
             Console.Read();
         }
     }

  把序列化和把序列化为二进制文件的方法封装成泛型方法

class Program
     {
         static void Main(string[] args)
         {
             Book book = new Book() { ID = 101, Name = "C#程序设计", Price = 79.5f };
             //序列化文件
             Serializer.ObjectToFile(book, @"c:\book.txt");
 
             //反序列化文件
             Book outBook = Serializer.FileToObject<Book>(@"c:\book.txt") as Book;
             Console.WriteLine(outBook.ID);
             Console.WriteLine(outBook.Name);
             Console.WriteLine(outBook.Price);
             Console.Read();
         }
     }
 
     public class Serializer
     {
         #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 = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                 return result;
             }
         }
 
         /// <summary>
         /// 将对象序列化为文件
         /// </summary>
         /// <typeparam name="T">类型</typeparam>
         /// <param name="t">实例</param>
         /// <param name="path">存放路径</param>
         public static void ObjectToFile<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 = System.Text.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 FileToObject<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
     }
 
     [Serializable]
     public class Book
     {
         public int ID { get; set; }
         public string Name { get; set; }
         public float Price { get; set; }
     }

 

转自:http://www.cnblogs.com/maitian-lf/p/3670570.html

 

posted @ 2018-04-04 10:01  youguess  阅读(175)  评论(0编辑  收藏  举报