In JavaScriptSerializer, we can see the following methods or constructor, they are all instance methods:
Member |
Description |
JavaScriptSerializer () |
Create a new JavaScriptSerializer object without specifying JavaScriptTypeResolver. |
JavaScriptSerializer (JavaScriptTypeResolver) |
The constructor is used to create a new JavaScriptSerializer object and map a specific type and identity string using the specified JavaScriptTypeResolver. |
ConvertToType <T> (Object) |
Converts a given object to type T. |
Deserialize <T> (String) |
Converts a JSON string to type T. |
DeserializeObject (String) |
Converts a JSON string into an object. |
MaxJsonLength |
Gets or sets the maximum length of the JSON string that can be accepted during serialization. |
RecursionLimit |
Obtain or set the maximum recursion depth when deserializing a json string. |
RegisterConverters (IEnumerable <JavaScriptConverter>) |
Register the JavaScriptConveter object used during serialization. |
Serialize (Object) |
Serialize an object into a JSON string. |
Serialize (Object, StringBuilder) |
Serialize an object to a StringBuilder. |
public class UserInfo {
public Int32 Id { get; set; }
public String UserName { get; set; }
public DateTime Time { get; set; }
public bool Gender { get; set; } }
Next, write the following code in Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
UserInfo info = new UserInfo();
info.Id = 1;
Info. UserName = "modembo http://maoblog.com ";
info.Time = DateTime.Now;
info.Gender = true;
System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
String strJson = jss.Serialize(info);
Response.Write(strJson);
// Output result:
// {"Id": 1, "UserName": "maobo http://maoblog.com", "Time": "\/Date (1297950721668 \/", "Gender": true}
UserInfo info2 = jss.Deserialize<UserInfo>(strJson);
Response.Write(String.Format("<br/>{0}<br/>{1}<br/>{2}<br/>{3}", info2.Id, info2.UserName, info2.Time, info2.Gender));
Response.End();
// Result: // 1 // modembo http://maoblog.com // 14:00:29 // True}