SerializeHelper.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.Runtime.Serialization.Json;
  8. using System.Text;
  9. using System.Xml;
  10. using System.Xml.Serialization;
  11. namespace Venus_Unity
  12. {
  13. public class SerializeHelper
  14. {
  15. private static SerializeHelper m_Instance;
  16. public static SerializeHelper Instance
  17. {
  18. get
  19. {
  20. if (m_Instance == null)
  21. {
  22. m_Instance = new SerializeHelper();
  23. }
  24. return m_Instance;
  25. }
  26. }
  27. public SerializeHelper()
  28. { }
  29. #region XML序列化
  30. /// <summary>
  31. /// 文件化XML序列化
  32. /// </summary>
  33. /// <param name="obj">对象</param>
  34. /// <param name="filename">文件路径</param>
  35. public void Save(object obj, string filename)
  36. {
  37. FileStream fs = null;
  38. try
  39. {
  40. fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
  41. //Create our own namespaces for the output
  42. XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
  43. //Add an empty namespace and empty value
  44. ns.Add("", "");
  45. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  46. serializer.Serialize(fs, obj, ns);
  47. }
  48. catch (Exception ex)
  49. {
  50. throw ex;
  51. }
  52. finally
  53. {
  54. if (fs != null) fs.Close();
  55. }
  56. }
  57. /// <summary>
  58. /// 文件化XML反序列化
  59. /// </summary>
  60. /// <param name="type">对象类型</param>
  61. /// <param name="filename">文件路径</param>
  62. public object Load(Type type, string filename)
  63. {
  64. FileStream fs = null;
  65. try
  66. {
  67. fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  68. XmlSerializer serializer = new XmlSerializer(type);
  69. return serializer.Deserialize(fs);
  70. }
  71. catch (Exception ex)
  72. {
  73. throw ex;
  74. }
  75. finally
  76. {
  77. if (fs != null) fs.Close();
  78. }
  79. }
  80. /// <summary>
  81. /// 文本化XML序列化
  82. /// </summary>
  83. /// <param name="item">对象</param>
  84. public string ToXml<T>(T item)
  85. {
  86. XmlSerializer serializer = new XmlSerializer(item.GetType());
  87. StringBuilder sb = new StringBuilder();
  88. using (XmlWriter writer = XmlWriter.Create(sb))
  89. {
  90. serializer.Serialize(writer, item);
  91. return sb.ToString();
  92. }
  93. }
  94. /// <summary>
  95. /// 文本化XML反序列化
  96. /// </summary>
  97. /// <param name="str">字符串序列</param>
  98. public T FromXml<T>(string str)
  99. {
  100. XmlSerializer serializer = new XmlSerializer(typeof(T));
  101. using (XmlReader reader = new XmlTextReader(new StringReader(str)))
  102. {
  103. return (T)serializer.Deserialize(reader);
  104. }
  105. }
  106. #endregion
  107. #region BinaryFormatter序列化
  108. /// <summary>
  109. /// BinaryFormatter序列化
  110. /// </summary>
  111. /// <param name="item">对象</param>
  112. public string ToBinary<T>(T item)
  113. {
  114. BinaryFormatter formatter = new BinaryFormatter();
  115. using (MemoryStream ms = new MemoryStream())
  116. {
  117. formatter.Serialize(ms, item);
  118. ms.Position = 0;
  119. byte[] bytes = ms.ToArray();
  120. StringBuilder sb = new StringBuilder();
  121. foreach (byte bt in bytes)
  122. {
  123. sb.Append(string.Format("{0:X2}", bt));
  124. }
  125. return sb.ToString();
  126. }
  127. }
  128. /// <summary>
  129. /// BinaryFormatter反序列化
  130. /// </summary>
  131. /// <param name="str">字符串序列</param>
  132. public T FromBinary<T>(string str)
  133. {
  134. int intLen = str.Length / 2;
  135. byte[] bytes = new byte[intLen];
  136. for (int i = 0; i < intLen; i++)
  137. {
  138. int ibyte = Convert.ToInt32(str.Substring(i * 2, 2), 16);
  139. bytes[i] = (byte)ibyte;
  140. }
  141. BinaryFormatter formatter = new BinaryFormatter();
  142. using (MemoryStream ms = new MemoryStream(bytes))
  143. {
  144. return (T)formatter.Deserialize(ms);
  145. }
  146. }
  147. #endregion
  148. /// <summary>
  149. /// 将对象序列化为二进制字节
  150. /// </summary>
  151. /// <param name="obj">待序列化的对象</param>
  152. /// <returns></returns>
  153. public byte[] SerializeToBinary(object obj)
  154. {
  155. byte[] bytes = new byte[2500];
  156. using (MemoryStream memoryStream = new MemoryStream())
  157. {
  158. BinaryFormatter bformatter = new BinaryFormatter();
  159. bformatter.Serialize(memoryStream, obj);
  160. memoryStream.Seek(0, 0);
  161. if (memoryStream.Length > bytes.Length)
  162. {
  163. bytes = new byte[memoryStream.Length];
  164. }
  165. bytes = memoryStream.ToArray();
  166. }
  167. return bytes;
  168. }
  169. /// <summary>
  170. /// 从二进制字节中反序列化为对象
  171. /// </summary>
  172. /// <param name="type">对象的类型</param>
  173. /// <param name="bytes">字节数组</param>
  174. /// <returns>反序列化后得到的对象</returns>
  175. public object DeserializeFromBinary(Type type, byte[] bytes)
  176. {
  177. object result = new object();
  178. using (MemoryStream memoryStream = new MemoryStream(bytes))
  179. {
  180. BinaryFormatter serializer = new BinaryFormatter();
  181. result = serializer.Deserialize(memoryStream);
  182. }
  183. return result;
  184. }
  185. /// <summary>
  186. /// 将文件对象序列化到文件中
  187. /// </summary>
  188. /// <param name="obj">待序列化的对象</param>
  189. /// <param name="path">文件路径</param>
  190. /// <param name="fileMode">文件打开模式</param>
  191. public void SerializeToBinary(object obj, string path, FileMode fileMode)
  192. {
  193. using (FileStream fs = new FileStream(path, fileMode))
  194. {
  195. // Construct a BinaryFormatter and use it to serialize the data to the stream.
  196. BinaryFormatter formatter = new BinaryFormatter();
  197. formatter.Serialize(fs, obj);
  198. }
  199. }
  200. /// <summary>
  201. /// 将文件对象序列化到文件中
  202. /// </summary>
  203. /// <param name="obj">待序列化的对象</param>
  204. /// <param name="path">文件路径</param>
  205. public void SerializeToBinary(object obj, string path)
  206. {
  207. SerializeToBinary(obj, path, FileMode.Create);
  208. }
  209. /// <summary>
  210. /// 从二进制文件中反序列化为对象
  211. /// </summary>
  212. /// <param name="type">对象的类型</param>
  213. /// <param name="path">二进制文件路径</param>
  214. /// <returns>反序列化后得到的对象</returns>
  215. public object DeserializeFromBinary(Type type, string path)
  216. {
  217. object result = new object();
  218. using (FileStream fileStream = new FileStream(path, FileMode.Open))
  219. {
  220. BinaryFormatter serializer = new BinaryFormatter();
  221. result = serializer.Deserialize(fileStream);
  222. }
  223. return result;
  224. }
  225. /// <summary>
  226. /// 获取对象的转换为二进制的字节大小
  227. /// </summary>
  228. /// <param name="obj"></param>
  229. /// <returns></returns>
  230. public long GetByteSize(object obj)
  231. {
  232. long result;
  233. BinaryFormatter bFormatter = new BinaryFormatter();
  234. using (MemoryStream stream = new MemoryStream())
  235. {
  236. bFormatter.Serialize(stream, obj);
  237. result = stream.Length;
  238. }
  239. return result;
  240. }
  241. /// <summary>
  242. /// 克隆一个对象
  243. /// </summary>
  244. /// <param name="obj">待克隆的对象</param>
  245. /// <returns>克隆的一个新的对象</returns>
  246. public object Clone(object obj)
  247. {
  248. object cloned = null;
  249. BinaryFormatter bFormatter = new BinaryFormatter();
  250. using (MemoryStream memoryStream = new MemoryStream())
  251. {
  252. try
  253. {
  254. bFormatter.Serialize(memoryStream, obj);
  255. memoryStream.Seek(0, SeekOrigin.Begin);
  256. cloned = bFormatter.Deserialize(memoryStream);
  257. }
  258. catch //(Exception e)
  259. {
  260. ;
  261. }
  262. }
  263. return cloned;
  264. }
  265. /// <summary>
  266. /// 从文件中读取文本内容
  267. /// </summary>
  268. /// <param name="path">文件路径</param>
  269. /// <returns>文件的内容</returns>
  270. public string ReadFile(string path)
  271. {
  272. string content = string.Empty;
  273. using (StreamReader reader = new StreamReader(path))
  274. {
  275. content = reader.ReadToEnd();
  276. }
  277. return content;
  278. }
  279. private byte[] compress(byte[] bytes)
  280. {
  281. using (MemoryStream ms = new MemoryStream())
  282. {
  283. using (DeflateStream gzs = new DeflateStream(ms, CompressionMode.Compress, false))
  284. {
  285. gzs.Write(bytes, 0, bytes.Length);
  286. }
  287. ms.Close();
  288. return ms.GetBuffer();
  289. }
  290. }
  291. private byte[] decompress(byte[] bytes)
  292. {
  293. using (MemoryStream ms = new MemoryStream(bytes, false))
  294. {
  295. using (DeflateStream gzs = new DeflateStream(ms, CompressionMode.Decompress, false))
  296. {
  297. using (MemoryStream dest = new MemoryStream())
  298. {
  299. byte[] tmp = new byte[bytes.Length];
  300. int read;
  301. while ((read = gzs.Read(tmp, 0, tmp.Length)) != 0)
  302. {
  303. dest.Write(tmp, 0, read);
  304. }
  305. dest.Close();
  306. return dest.GetBuffer();
  307. }
  308. }
  309. }
  310. }
  311. /// <summary>
  312. /// 序列化成一个字符串
  313. /// </summary>
  314. /// <typeparam name="T"></typeparam>
  315. /// <param name="entity"></param>
  316. /// <returns></returns>
  317. public string XMLSerializeToString<T>(T entity)
  318. {
  319. StringBuilder buffer = new StringBuilder();
  320. XmlSerializer serializer = new XmlSerializer(typeof(T));
  321. using (TextWriter writer = new StringWriter(buffer))
  322. {
  323. serializer.Serialize(writer, entity);
  324. }
  325. return buffer.ToString();
  326. }
  327. /// <summary>
  328. /// xml字符串反序列化为一个XML文件
  329. /// </summary>
  330. /// <typeparam name="T"></typeparam>
  331. /// <param name="xmlString"></param>
  332. /// <returns></returns>
  333. public T DeXMLSerialize<T>(string xmlString)
  334. {
  335. T cloneObject = default(T);
  336. StringBuilder buffer = new StringBuilder();
  337. buffer.Append(xmlString);
  338. XmlSerializer serializer = new XmlSerializer(typeof(T));
  339. using (TextReader reader = new StringReader(buffer.ToString()))
  340. {
  341. Object obj = serializer.Deserialize(reader);
  342. cloneObject = (T)obj;
  343. }
  344. return cloneObject;
  345. }
  346. /// <summary>
  347. /// Json转换成对象
  348. /// </summary>
  349. /// <typeparam name="T"></typeparam>
  350. /// <param name="jsonText"></param>
  351. /// <returns></returns>
  352. public T JsonStringToObject<T>(string jsonText)
  353. {
  354. DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
  355. MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
  356. T obj = (T)s.ReadObject(ms);
  357. ms.Dispose();
  358. return obj;
  359. }
  360. /// <summary>
  361. /// 对象转换成JSON
  362. /// </summary>
  363. /// <typeparam name="T"></typeparam>
  364. /// <param name="obj"></param>
  365. /// <returns></returns>
  366. public string ObjectToJsonString<T>(T obj)
  367. {
  368. string result = string.Empty;
  369. try
  370. {
  371. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
  372. using (MemoryStream ms = new MemoryStream())
  373. {
  374. serializer.WriteObject(ms, obj);
  375. ms.Position = 0;
  376. using (StreamReader read = new StreamReader(ms))
  377. {
  378. result = read.ReadToEnd();
  379. }
  380. }
  381. }
  382. catch (Exception ex)
  383. {
  384. throw new Exception(" 对象转换成JSON失败!" + ex.Message);
  385. }
  386. return result;
  387. }
  388. /// <summary>
  389. /// 类对象保存为Json文件
  390. /// </summary>
  391. /// <typeparam name="T"></typeparam>
  392. /// <param name="obj"></param>
  393. /// <param name="strFilePath"></param>
  394. /// <returns></returns>
  395. public bool WriteToJsonFile<T>(T obj, string strFilePath)
  396. {
  397. bool bRes = false;
  398. try
  399. {
  400. string strJson = ObjectToJsonString(obj);
  401. //File.WriteAllText(strFilePath, strJson, Encoding.UTF8);
  402. WriteToJsonFile(strJson, strFilePath);
  403. bRes = true;
  404. }
  405. catch (Exception ex)
  406. {
  407. throw new Exception("Write Json File Fail!" + ex.Message);
  408. }
  409. return bRes;
  410. }
  411. /// <summary>
  412. /// Json文件转换为类对象
  413. /// </summary>
  414. /// <typeparam name="T"></typeparam>
  415. /// <param name="strFilePath"></param>
  416. /// <returns></returns>
  417. public T ReadFromJsonFile<T>(string strFilePath)
  418. {
  419. if (File.Exists(strFilePath))
  420. {
  421. try
  422. {
  423. string strJson = File.ReadAllText(strFilePath);
  424. return JsonStringToObject<T>(strJson);
  425. }
  426. catch (Exception ex)
  427. {
  428. throw new Exception("Read Json File Fail!" + ex.Message);
  429. }
  430. }
  431. else
  432. {
  433. throw new Exception("File is not Exit!");
  434. }
  435. }
  436. /// <summary>
  437. /// 对象转换成JSON,并保存文件
  438. /// </summary>
  439. /// <param name="obj"></param>
  440. /// <param name="path"></param>
  441. public void WriteToJsonFile(string content, string path)
  442. {
  443. FileInfo fi = new FileInfo(path);
  444. var di = fi.Directory;
  445. if (!di.Exists)
  446. {
  447. di.Create();
  448. }
  449. if (!File.Exists(path)) // 判断是否已有相同文件
  450. {
  451. FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
  452. fs1.Flush();
  453. fs1.Dispose();
  454. fs1.Close();
  455. }
  456. File.WriteAllText(path, ConvertJsonString(content));
  457. }
  458. /// <summary>
  459. /// 格式化json字符串
  460. /// </summary>
  461. /// <param name="str"></param>
  462. /// <returns></returns>
  463. private string ConvertJsonString(string str)
  464. {
  465. JsonSerializer serializer = new JsonSerializer();
  466. TextReader tr = new StringReader(str);
  467. JsonTextReader jtr = new JsonTextReader(tr);
  468. object obj = serializer.Deserialize(jtr);
  469. if (obj != null)
  470. {
  471. StringWriter textWriter = new StringWriter();
  472. JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
  473. {
  474. Formatting = Newtonsoft.Json.Formatting.Indented,
  475. Indentation = 4,
  476. IndentChar = ' '
  477. };
  478. serializer.Serialize(jsonWriter, obj);
  479. return textWriter.ToString();
  480. }
  481. else
  482. {
  483. return str;
  484. }
  485. }
  486. public static T DeepCopyJson<T>(T obj)
  487. {
  488. return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(obj));
  489. }
  490. public string DictionaryToString(Dictionary<string, string> keyValuePairs)
  491. {
  492. StringBuilder sb = new StringBuilder();
  493. foreach (var item in keyValuePairs)
  494. {
  495. if (sb.Length > 0)
  496. {
  497. sb.Append(";");
  498. }
  499. sb.Append($"{item.Key}:{item.Value}");
  500. }
  501. return sb.ToString();
  502. }
  503. public Dictionary<string, string> StringToDictionary(string str)
  504. {
  505. Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
  506. string[] strings = str.Split(';');
  507. for (int i = 0; i < strings.Length; i++)
  508. {
  509. string[] keyValue = strings[i].Split(':');
  510. if (keyValue.Length != 2)
  511. {
  512. return new Dictionary<string, string>();
  513. }
  514. keyValuePairs.Add(keyValue[0], keyValue[1]);
  515. }
  516. return keyValuePairs;
  517. }
  518. }
  519. }