Asp.net JavaScriptSerializer for serialization and deserialization

Source: Internet
Author: User

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 );

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.