Posted By

marcocs on 07/29/09


Tagged

serialization


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

umang_nine
pckujawa
khouser
Beppoi


Serialize/Deserialize


 / Published in: C#
 

Utilidad de serialización de objetos; Utiliza este class para crear datos xml a partir de un prototipo;

  1. namespace You.Xml
  2. {
  3. #region IMPORTS
  4.  
  5. using System;
  6. using System.IO;
  7. using System.Text;
  8. using System.Xml;
  9. using System.Xml.Serialization;
  10.  
  11. #endregion
  12.  
  13. /// <summary>
  14. /// Utilidad de serialización de objetos;
  15. /// Se utiliza este class para crear set de datos xml a partir de un prototipo;
  16. /// </summary>
  17. public class XmlSerialization
  18. {
  19. /// <summary>
  20. /// Serializa un objeto utilizando el tipo especificado.
  21. /// </summary>
  22. /// <param name="pObject">objeto a serializar</param>
  23. /// <param name="type">tipo de objeto a serializar</param>
  24. /// <returns>string (xml)</returns>
  25. public static string Serialize(object pObject, Type type)
  26. {
  27. try
  28. {
  29. String XmlizedString = null;
  30. MemoryStream memoryStream = new MemoryStream();
  31. XmlSerializer xs = new XmlSerializer(type);
  32. using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
  33. {
  34. xs.Serialize(xmlTextWriter, pObject);
  35. memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
  36. XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
  37. }
  38. return XmlizedString;
  39. }
  40. catch (Exception) { return null; }
  41. }
  42.  
  43. /// <summary>
  44. /// Deserializa una string xml UTF8 en un objeto
  45. /// </summary>
  46. /// <param name="data">string xml</param>
  47. /// <param name="type">tipo a serializar</param>
  48. /// <returns>objeto deserializado</returns>
  49. public static object Deserialize(string data, Type type)
  50. {
  51. using (TextReader rd = new StringReader(data))
  52. {
  53. XmlSerializer sr = new XmlSerializer(type);
  54. return sr.Deserialize(rd);
  55. }
  56. }
  57.  
  58. /// <summary>
  59. /// Conversión de byte[] a strings UTF8
  60. /// </summary>
  61. /// <param name="characters">byte[] a convertir</param>
  62. /// <returns>string</returns>
  63. static string UTF8ByteArrayToString(byte[] characters)
  64. {
  65. String constructedString = new UTF8Encoding().GetString(characters);
  66. return (constructedString);
  67. }
  68.  
  69. /// <summary>
  70. /// Conversión de un string UTF8 a byte[];
  71. /// </summary>
  72. /// <param name="pXmlString">string a convertir.</param>
  73. /// <returns>byte[] del estring</returns>
  74. static byte[] StringToUTF8ByteArray(String pXmlString)
  75. {
  76. byte[] byteArray = new UTF8Encoding().GetBytes(pXmlString);
  77. return byteArray;
  78. }
  79.  
  80. }
  81. }

Report this snippet  

You need to login to post a comment.