C # conversion of several formats of serialization and deserialization,

Source: Internet
Author: User

C # conversion of several formats of serialization and deserialization,

The conversion between serialization and deserialization is introduced here.

First, we will introduce how to serialize objects. There are two common methods to serialize objects: string and xml objects;

The first method is to convert an object to a string object. This is simple and there is nothing to talk about;

 public string ScriptSerialize<T>(T t)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            return serializer.Serialize(t);        }


Second, convert an object to an xml object:

 
 public string ScriptSerializeToXML<T>(T t)        {            XmlSerializer serializer = new XmlSerializer(typeof(T));            MemoryStream mem = new MemoryStream();            XmlTextWriter writer = new XmlTextWriter(mem,Encoding.UTF8);            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();            ns.Add("","");            serializer.Serialize(writer,t,ns);            writer.Close();            return Encoding.UTF8.GetString(mem.ToArray());        }
 

The following describes how to deserialize A string object into a corresponding object;

1. deserialize A string object into an object

 public T ScriptDeserialize<T>(string strJson)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            return serializer.Deserialize<T>(strJson);        }

Ii. deserializing string objects into list objects

 public List<T> JSONStringToList<T>(string strJson)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            List<T> objList = serializer.Deserialize<List<T>>(strJson);            return objList;        }

Iii. deserializing A string object to a able object

 
Public DataTable JSONStringToDataTable <T> (string strJson) {DataTable dt = new DataTable (); if (strJson. indexOf ("[")>-1) // if the value is greater than, strJson stores Multiple model Objects {strJson = strJson. remove (strJson. length-1, 1 ). remove (0, 1 ). replace ("},{", "};{") ;}javascriptserializer serializer = new JavaScriptSerializer (); string [] items = strJson. split (';'); foreach (PropertyInfo property in typeof (T ). getProperties () // obtain all attributes of the T type through reflection {DataColumn col = new DataColumn (property. name, property. propertyType); dt. columns. add (col) ;}// loop one by one deserialization for (int I = 0; I <items. length; I ++) {DataRow dr = dt. newRow (); // deserialize a T-type object T temp = serializer. deserialize <T> (items [I]); foreach (PropertyInfo property in typeof (T ). getProperties () {dr [property. name] = property. getValue (temp, null);} dt. rows. add (dr) ;}return dt ;}
 

Iv. deserializing xml objects into object objects

 
 public T JSONXMLToObject<T>(string strJson)        {            XmlDocument xdoc = new XmlDocument();            try            {                xdoc.LoadXml(strJson);                XmlNodeReader reader = new XmlNodeReader(xdoc.DocumentElement);                XmlSerializer ser = new XmlSerializer(typeof(T));                object obj = ser.Deserialize(reader);                return (T)obj;            }            catch            {                return default(T);            }        }
 

How can I call specific instances? Pay special attention to the deserialization of the objcet object of the xml object.

 public class LoginObject    {          public string Account { get; set;}          public string Password { get; set;}     }

 

 
1 LoginObject loginObject = new LoginObject {Account = account, Password = password}; 2 ExTools. manage. class. CScriptSerialize Serialize = new Class. CScriptSerialize (); 3 // convert the object to string 4 string strJson = Serialize. scriptSerialize (loginObject); 5 6 // convert an object to an xml object 7 string strJson = Serialize. scriptSerializeToXML (loginObject); 8 9 10 // convert to list object 11 List <LoginObject> list = Serialize. JSONStringToList <LoginObject> (strJson); 12 // convert an xml object to object 13 strJson = strJson. substring (1, strJson. length-1); 14 loginObject = Serialize. JSONXMLToObject <LoginObject> (strJson); 15 // convert the string to dataTable16 DataTable dt = Serialize. JSONStringToDataTable <LoginObject> (strJson); 17 // convert a string to an object 18 loginObject = Serialize. scriptDeserialize <LoginObject> (strJson );
 

Related Article

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.