Implemented through JavaScriptSerializer. Its namespace is: System. Web. Script. Serialization
To use it, you must also add
System. Web. Extensions library file reference
Reference object class: Customer
Public class Customer
{
Public int Unid {get; set ;}
Public string CustomerName {get; set ;}
}
Description: used to provide serialization and deserialization functions for AFAX-enabled applications.
(1) serialization
Method: public string Serialize (Object obj), used to convert an Object to a JSON string
Public string ScriptSerialize (Customer customer)
{
JavaScriptSerializer js = new JavaScriptSerializer ();
Return js. Serialize (customer );
}
Test
Customer cc = new Customer {Unid = 1, CustomerName = "John "};
String strJson = ScriptSerialize (cc );
Console. WriteLine (strJson );
(2) deserialization
Public Customer ScriptDeserialize (string strJson)
{
JavaScriptSerializer js = new JavaScriptSerializer ();
Return js. Deserialize <Customer> (strJson );
}
Implemented using the Deserialize <T> method.
Test:
Customer c1 = ScriptDeserialize (strJson );
Console. WriteLine (c1.Unid + "" + c1.CustomerName );
(3) method generics
Public string ScriptSerialize <T> (T t)
{
JavaScriptSerializer js = new JavaScriptSerializer ();
Return js. Serialize (t );
}
Public T ScriptDeserialize <T> (string strJson)
{
JavaScriptSerializer js = new JavaScriptSerializer ();
Return js. Deserialize <T> (strJson );
}
Test:
Customer cc = new Customer {Unid = 1, CustomerName = "John "};
String strJson = ScriptSerialize <Customer> (cc );
Console. WriteLine (strJson );
Customer c1 = ScriptDeserialize <Customer> (strJson );
Console. WriteLine (c1.Unid + "" + c1.CustomerName );