序列化:将实体对象序列化为指定格式,如序列化为XML文件又或者是序列化为JSON字符串等。
反序列化:将XML文件或者JSON字符串等转换为实体对象。
准备实体数据
1.首先新建一个控制台工程,建立实体Company(公司类)、Employee(员工类)、ESex(性别枚举)
- public class Company
- {
- /// <summary>
- /// 公司名称
- /// </summary>
- public string Name { get; set; }
- /// <summary>
- /// 注册时间
- /// </summary>
- public DateTime RegistrationTime { get; set; }
- /// <summary>
- /// 注册资金
- /// </summary>
- public int RegistrationCapital { get; set; }
- /// <summary>
- /// 公司员工
- /// </summary>
- public List<Employee> employees { get; set; }
-
- public override string ToString()
- {
- return string.Format("Name:{0}\nRegistrationTime:{1}\nRegistrationCapital:{2}\nemployeesNumber:{3}",Name,RegistrationTime.ToString("yyyy-MM-dd HH:mm:ss"),RegistrationCapital,employees.Count());
- }
- }
- public class Employee
- {
- /// <summary>
- ///员工名称
- /// </summary>
- public string Name { get; set; }
- /// <summary>
- /// 入职时间
- /// </summary>
- public DateTime InductionTime { get; set; }
- /// <summary>
- /// 年龄
- /// </summary>
- public int Age { get; set; }
- /// <summary>
- /// 性别
- /// </summary>
- public ESex Sex { get; set; }
- public override string ToString()
- {
- return string.Format("Name:{0}\nInductionTime:{1}\nAge:{2}\nSex:{3}",InductionTime.ToString("yyyy-MM-dd HH:mm:ss"),Age,Sex);
- }
- }
- public enum ESex
- {
- man,woman
- }
2.准备测试数据
- #region 准备测试数据
- List<Employee> ems = new List<Employee>() {
- new Employee(){ Age=22,InductionTime=new DateTime(2012,2,1),Name="张三",Sex=ESex.man},new Employee(){ Age=32,5,Name="李四",new Employee(){ Age=18,InductionTime=new DateTime(2014,7,5),Name="赵婷",Sex=ESex.woman}
- };
- Company company = new Company()
- {
- Name = "上海点点乐信息科技有限公司",RegistrationCapital = 5000000,RegistrationTime = new DateTime(2012,1,employees = ems
-
- };
- #endregion
序列化XML
对于XML的序列化和反序列化我们需要用到System.Xml.Serialization.XmlSerializer 类
分析需求得出,需要将什么类型的对象序列化为XML,XML文件的保存路径是什么,如果当前路径目录不存在,还需要先创建目录。
- /// <summary>
- /// 创建目录和文件
- /// </summary>
- /// <param name="path">路径</param>
- /// <param name="isfile">路径是否是文件(默认是)</param>
- /// <returns></returns>
- public static bool CreateFileToDirectory(string path,bool isfile = true)
- {
- FileStream fs = null;
- try
- {
- if (!isfile)
- {
- if (!System.IO.Directory.Exists(path))
- Directory.CreateDirectory(path);
- }
- else
- {
- string directorypath = path.Substring(0,path.LastIndexOf("/"));//截取目录
- if (!System.IO.Directory.Exists(directorypath))
- Directory.CreateDirectory(directorypath);
-
- if (!System.IO.File.Exists(path))
- fs = File.Create(path);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (fs != null)
- fs.Close();
- }
- return true;
- }
- /// <summary>
- /// 序列化为XML
- /// </summary>
- /// <param name="obj">序列化对象</param>
- /// <param name="filepath">XML保存路径</param>
- /// <returns>返回true序列化成功,否则失败</returns>
- public static bool SerializeXml(Object obj,string filepath)
- {
- bool result = false;
- FileStream fs = null;
- try
- {
- CreateFileToDirectory(filepath);
- fs = new FileStream(filepath,FileMode.Create,FileAccess.Write,FileShare.ReadWrite);
- System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
- serializer.Serialize(fs,obj);
- result = true;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (fs != null)
- fs.Close();
- }
- return result;
- }
反序列化XML
需要将那个路径的XML文件反序列化为什么类型的实体对象?
- /// <summary>
- /// 反序列化XML
- /// </summary>
- /// <param name="type">反序列化的类型</param>
- /// <param name="filepath">XML文件路径</param>
- /// <returns>返回obj对象</returns>
- public static object DeserializeXml(Type type,string filepath)
- {
- FileStream fs = null;
- try
- {
- fs = new FileStream(filepath,FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
- System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
- return serializer.Deserialize(fs);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (fs != null)
- fs.Close();
- }
- }
- /// <summary>
- /// 反序列化XML
- /// </summary>
- /// <typeparam name="T">类型参数</typeparam>
- /// <param name="type">反序列化的类型</param>
- /// <param name="filepath">XML文件路径</param>
- /// <returns>返回T类型对象</returns>
- public static T DeserializeXml<T>(string filepath)
- {
- FileStream fs = null;
- try
- {
- fs = new FileStream(filepath,FileShare.ReadWrite);
- System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
- return (T)serializer.Deserialize(fs);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (fs != null)
- fs.Close();
- }
- }
序列化和反序列化JSON
序列化JSON需要用到 Newtonsoft.Json.dll库,可在引用上右键管理Nuget程序搜索json.net来安装引用
- /// <summary>
- /// 序列化为JSON
- /// </summary>
- /// <param name="obj">序列化对象</param>
- /// <returns>返回json字符串</returns>
- public static string SerializeJson(Object obj)
- {
- return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
- }
- /// <summary>
- /// 反序列化JSON
- /// </summary>
- /// <typeparam name="T">类型参数</typeparam>
- /// <param name="value">json字符串</param>
- /// <returns>返回T类型对象对象</returns>
- public static T DeserializeJson<T>(string value)
- {
- return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
- }
完整代码
IOHelper.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
-
- namespace ConsoleApplication38
- {
- public sealed class IOHelper
- {
- /// <summary>
- /// 反序列化XML
- /// </summary>
- /// <param name="type">反序列化的类型</param>
- /// <param name="filepath">XML文件路径</param>
- /// <returns>返回obj对象</returns>
- public static object DeserializeXml(Type type,FileShare.ReadWrite);
- System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
- return (T)serializer.Deserialize(fs);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (fs != null)
- fs.Close();
- }
- }
- /// <summary>
- /// 序列化为XML
- /// </summary>
- /// <param name="obj">序列化对象</param>
- /// <param name="filepath">XML保存路径</param>
- /// <returns>返回true序列化成功,否则失败</returns>
- public static bool SerializeXml(Object obj,obj);
- result = true;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (fs != null)
- fs.Close();
- }
- return result;
- }
- /// <summary>
- /// 序列化为JSON
- /// </summary>
- /// <param name="obj">序列化对象</param>
- /// <returns>返回json字符串</returns>
- public static string SerializeJson(Object obj)
- {
- return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
- }
- /// <summary>
- /// 反序列化JSON
- /// </summary>
- /// <typeparam name="T">类型参数</typeparam>
- /// <param name="value">json字符串</param>
- /// <returns>返回T类型对象对象</returns>
- public static T DeserializeJson<T>(string value)
- {
- return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
- }
- /// <summary>
- /// 创建目录和文件
- /// </summary>
- /// <param name="path">路径</param>
- /// <param name="isfile">路径是否是文件(默认是)</param>
- /// <returns></returns>
- public static bool CreateFileToDirectory(string path,path.LastIndexOf("/"));//截取目录
- if (!System.IO.Directory.Exists(directorypath))
- Directory.CreateDirectory(directorypath);
-
- if (!System.IO.File.Exists(path))
- fs = File.Create(path);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- if (fs != null)
- fs.Close();
- }
- return true;
- }
- }
- }
Program.cs
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace ConsoleApplication38
- {
- class Program
- {
- static void Main(string[] args)
- {
- #region 准备测试数据
- List<Employee> ems = new List<Employee>() {
- new Employee(){ Age=22,employees = ems
-
- };
- #endregion
-
- #region 序列化XML
- if (IOHelper.SerializeXml(company,"../Config/CompanyConfig.config"))
- Console.WriteLine("序列化成功");
- else
- Console.WriteLine("序列化失败");
- Console.WriteLine("===============================华丽的分割线===============================");
- if (IOHelper.SerializeXml(ems,"../Config/EmployeeConfig.config"))
- Console.WriteLine("序列化成功");
- else
- Console.WriteLine("序列化失败");
- #endregion
-
- Console.WriteLine("===============================华丽的分割线===============================");
-
- #region 反序列化XML
- Company x_company = (Company)IOHelper.DeserializeXml(typeof(Company),"../Config/CompanyConfig.config");
- Console.WriteLine(x_company.ToString());
- foreach (var item in x_company.employees)
- {
- Console.WriteLine(item.ToString());
- }
-
- Console.WriteLine("===============================华丽的分割线===============================");
-
- List<Employee> x_employees = IOHelper.DeserializeXml<List<Employee>>("../Config/EmployeeConfig.config");
- foreach (var item in x_employees)
- {
- Console.WriteLine(item.ToString());
- }
- #endregion
-
- Console.WriteLine("===============================华丽的分割线===============================");
-
- #region 序列化JSON
- string json_company = IOHelper.SerializeJson(company);
- Console.WriteLine(IOHelper.SerializeJson(json_company));
-
- Console.WriteLine("===============================华丽的分割线===============================");
-
- string json_ems = IOHelper.SerializeJson(ems);
- Console.WriteLine(json_ems);
- #endregion
-
- Console.WriteLine("===============================华丽的分割线===============================");
-
- #region 反序列化JSON
- Company j_company = IOHelper.DeserializeJson<Company>(json_company);
- Console.WriteLine(j_company.ToString());
- foreach (var item in j_company.employees)
- {
- Console.WriteLine(item.ToString());
- }
-
- Console.WriteLine("===============================华丽的分割线===============================");
-
- List<Employee> j_employees = IOHelper.DeserializeJson<List<Employee>>(json_ems);
- foreach (var item in j_employees)
- {
- Console.WriteLine(item.ToString());
- }
- #endregion
- }
-
- }
- public class Company
- {
- /// <summary>
- /// 公司名称
- /// </summary>
- public string Name { get; set; }
- /// <summary>
- /// 注册时间
- /// </summary>
- public DateTime RegistrationTime { get; set; }
- /// <summary>
- /// 注册资金
- /// </summary>
- public int RegistrationCapital { get; set; }
- /// <summary>
- /// 公司员工
- /// </summary>
- public List<Employee> employees { get; set; }
-
- public override string ToString()
- {
- return string.Format("Name:{0}\nRegistrationTime:{1}\nRegistrationCapital:{2}\nemployeesNumber:{3}",woman
- }
- }