. Net serialization and deserialization include XML, SOAP, binary, JSON

Source: Internet
Author: User
Tags net serialization tojson
  1. Using system;
  2. Using system. IO;
  3. Using system. runtime. serialization. formatters. Binary;
  4. Using system. runtime. serialization. formatters. Soap;
  5. Using system. runtime. serialization. JSON;
  6. Using system. text;
  7. Using system. xml;
  8. Using system. xml. serialization;
  9. Namespace common. serialization
  10. {
  11. Class serializehelper
  12. {
  13. # Region xmlserializer
  14. Public String toxml <t> (T item)
  15. {
  16. Xmlserializer serializer = new xmlserializer (item. GetType ());
  17. Stringbuilder sb = new stringbuilder ();
  18. Using (xmlwriter writer = xmlwriter. Create (SB ))
  19. {
  20. Serializer. serialize (writer, item );
  21. Return sb. tostring ();
  22. }
  23. }
  24. Public t fromxml <t> (string Str)
  25. {
  26. Xmlserializer serializer = new xmlserializer (typeof (t ));
  27. Using (xmlreader reader = new xmltextreader (New stringreader (STR )))
  28. {
  29. Return (t) serializer. deserialize (Reader );
  30. }
  31. }
  32. # Endregion
  33.  
  34. # Region binaryformatter
  35. Public String tobinary <t> (T item)
  36. {
  37. Binaryformatter formatter = new binaryformatter ();
  38. Using (memorystream MS = new memorystream ())
  39. {
  40. Formatter. serialize (MS, item );
  41. Ms. Position = 0;
  42. Byte [] bytes = Ms. toarray ();
  43. Stringbuilder sb = new stringbuilder ();
  44. Foreach (byte Bt in bytes)
  45. {
  46. SB. append (string. Format ("{0: X2}", BT ));
  47. }
  48. Return sb. tostring ();
  49. }
  50. }
  51. Public t frombinary <t> (string Str)
  52. {
  53. Int intlen = Str. Length/2;
  54. Byte [] bytes = new byte [intlen];
  55. For (INT I = 0; I <intlen; I ++)
  56. {
  57. Int ibyte = convert. toint32 (Str. substring (I * 2, 2), 16 );
  58. Bytes [I] = (byte) ibyte;
  59. }
  60. Binaryformatter formatter = new binaryformatter ();
  61. Using (memorystream MS = new memorystream (bytes ))
  62. {
  63. Return (t) formatter. deserialize (MS );
  64. }
  65. }
  66. # Endregion
  67.  
  68. # Region soapformatter
  69. Public String tosoap <t> (T item)
  70. {
  71. Soapformatter formatter = new soapformatter ();
  72. Using (memorystream MS = new memorystream ())
  73. {
  74. Formatter. serialize (MS, item );
  75. Ms. Position = 0;
  76. Xmldocument xmldoc = new xmldocument ();
  77. Xmldoc. Load (MS );
  78. Return xmldoc. innerxml;
  79. }
  80. }
  81. Public t fromsoap <t> (string Str)
  82. {
  83. Xmldocument xmldoc = new xmldocument ();
  84. Xmldoc. loadxml (STR );
  85. Soapformatter formatter = new soapformatter ();
  86. Using (memorystream MS = new memorystream ())
  87. {
  88. Xmldoc. Save (MS );
  89. Ms. Position = 0;
  90. Return (t) formatter. deserialize (MS );
  91. }
  92. }
  93. # Endregion
  94.  
  95.  
  96. # Region jsonserializer
  97. Public String tojson <t> (T item)
  98. {
  99. Datacontractjsonserializer serializer = new datacontractjsonserializer (item. GetType ());
  100. Using (memorystream MS = new memorystream ())
  101. {
  102. Serializer. writeobject (MS, item );
  103. Return encoding. utf8.getstring (Ms. toarray ());
  104. }
  105. }
  106. Public t fromjson <t> (string Str) where T: Class
  107. {
  108. Datacontractjsonserializer serializer = new datacontractjsonserializer (typeof (t ));
  109. Using (memorystream MS = new memorystream (encoding. utf8.getbytes (STR )))
  110. {
  111. Return serializer. readobject (MS) as t;
  112. }
  113. }
  114. # Endregion
  115. }
  116. }
using System;using System.IO;using System.Runtime.Serialization.Formatters.Binary;using System.Runtime.Serialization.Formatters.Soap;using System.Runtime.Serialization.Json;using System.Text;using System.Xml;using System.Xml.Serialization;namespace Common.Serialization{    class SerializeHelper    {        #region XmlSerializer        public string ToXml<T>(T item)        {            XmlSerializer serializer = new XmlSerializer(item.GetType());            StringBuilder sb = new StringBuilder();            using (XmlWriter writer = XmlWriter.Create(sb))            {                serializer.Serialize(writer, item);                return sb.ToString();            }        }        public T FromXml<T>(string str)        {            XmlSerializer serializer = new XmlSerializer(typeof(T));            using (XmlReader reader = new XmlTextReader(new StringReader(str)))            {                return (T)serializer.Deserialize(reader);            }        }        #endregion        #region BinaryFormatter        public string ToBinary<T>(T item)        {            BinaryFormatter formatter = new BinaryFormatter();            using (MemoryStream ms = new MemoryStream())            {                formatter.Serialize(ms, item);                ms.Position = 0;                byte[] bytes = ms.ToArray();                StringBuilder sb = new StringBuilder();                foreach (byte bt in bytes)                {                    sb.Append(string.Format("{0:X2}", bt));                }                return sb.ToString();            }        }        public T FromBinary<T>(string str)        {            int intLen = str.Length / 2;            byte[] bytes = new byte[intLen];            for (int i = 0; i < intLen; i++)            {                int ibyte = Convert.ToInt32(str.Substring(i * 2, 2), 16);                bytes[i] = (byte)ibyte;            }            BinaryFormatter formatter = new BinaryFormatter();            using (MemoryStream ms = new MemoryStream(bytes))            {                return (T)formatter.Deserialize(ms);            }        }        #endregion        #region SoapFormatter        public string ToSoap<T>(T item)        {            SoapFormatter formatter = new SoapFormatter();            using (MemoryStream ms = new MemoryStream())            {                formatter.Serialize(ms, item);                ms.Position = 0;                XmlDocument xmlDoc = new XmlDocument();                xmlDoc.Load(ms);                return xmlDoc.InnerXml;            }        }        public T FromSoap<T>(string str)        {            XmlDocument xmlDoc = new XmlDocument();            xmlDoc.LoadXml(str);            SoapFormatter formatter = new SoapFormatter();            using (MemoryStream ms = new MemoryStream())            {                xmlDoc.Save(ms);                ms.Position = 0;                return (T)formatter.Deserialize(ms);            }        }        #endregion        #region JsonSerializer        public string ToJson<T>(T item)        {            DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());            using (MemoryStream ms = new MemoryStream())            {                serializer.WriteObject(ms, item);                return Encoding.UTF8.GetString(ms.ToArray());            }        }        public T FromJson<T>(string str) where T : class        {            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))            {                return serializer.ReadObject(ms) as T;            }        }        #endregion    }}

These are all created on the class libraries provided by Microsoft. The namespace must be referenced during the call.

Tests on the Internet show that json.net is at least twice faster than the JSON speed provided by Microsoft, and supports LINQ to JSON. For more information, see:

Json.net Official Website: http://james.newtonking.com/projects/json-net.aspx
Json.net Introduction: http://www.cnblogs.com/jams742003/archive/2009/11/04/1595737.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.