JSON serialization analysis of ASP. NET Ajax framework programming

Source: Internet
Author: User
ASP. NET Ajax (initially Code The "Atlas" framework, as an open-source Ajax framework that mainly supports ASP. NET development platforms, was favored by a large number of. NET developers at its birth. In this article, we will focus on the analysis of data storage forms during the communication between servers and clients in ASP. NET Ajax programming. Specifically, we will discuss a server-side object that implements serialization and deserialization-javascriptserializer.

1. Introduction to JSON

Before formally discussing the JSON format, let's briefly recall the XML. XML is short for "Extensible Markup Language". It provides a method to define a series of data transmission protocols on the web, which is text-based, it is hailed as "an ideal way to fully develop the potential of the Internet and Web ".

So why should JSON be introduced in ASP. NET Ajax? Let's take a look at the example. For example, the current web page will load some address book information from the background. If the information is written in XML, it may be in the following format:

XML:

<Contact>
<Friend>
<Name> Michael </Name>
<Email> 17bity@gmail.com </Email>
<Homepage> http://www.jialing.net </Friend>
<Friend>
<Name> JOHN </Name>
<Email> john@gmail.com </Email>
<Homepage> http://www.john.com </Friend>
<Friend>
<Name> Peggy </Name>
<Email> peggy@gmail.com </Email>
<Homepage> http://www.peggy.com </Friend>
</Contact>

 

The JSON format is:

JSON

[
Friend :{
Name: "Michael ",
Email: 17bity@gmail.com ",
Homepage: "http://www.jialing.net"
},
Friend :{
Name: "John ",
Email: john@gmail.com ",
Homepage: "http://www.jobn.com"
},
Friend :{
Name: "Peggy ",
Email: peggy@gmail.com ",
Homepage: "http://www.peggy.com"
}
]

 

In contrast, the JSON expression is much simpler. In fact, what we are most concerned about is not only the simplicity of expression, but also how to simplify Dom parsing. Because the implementation of the XML/soap interpreter is different in different browsers, data in the same XML and soap formats may not necessarily get the same result. To this end, Asp. net Ajax specifically introduces a more lightweight JSON format and creates a consistent JSON parser. In addition, JavaScript itself supports object creation in JSON format. Therefore, all of this is obviously smooth and natural.

JSON, the JavaScript Object flag, has now become a built-in data format supported by JavaScript, which implements a more effective network data transfer method than the previous XML and soap. In short, JSON is a basic way to serialize objects into lightweight strings, and string data can be easily transmitted over the network without distortion. Let's take a look at the following simple C # class:

Public class user
{
String firstname;
String lastname;
}

Now, assume that the following instance of the above object is defined:

User USR = new user ();
USR. firstname = "John"
USR. lastname = "Smith ";

When the preceding data is serialized into JSON text, the following format is obtained:

{Firstname: "John"
Lastname: "Smith "}

 

Eval () or ASP. net Ajax. serialization. javascriptserializer class. We can deserialize JSON text strings in JavaScript code (that is, restore them to the original object form ).

In this article, we will focus on using ASP. net Ajax provides a special class to serialize a javascript object into a text string and then send it to the server, and how to use the server-side javascriptserializer class to deserialize the JSON text string into the original object data.

 

II. Key to sequence/deserialization-javascriptserializer

Namespace:System. Web. Script. serialization
ProgramSet:System. Web. Extensions(In system. Web. Extensions. dll)

The object implementing serialization and deserialization is javascriptserializer. Next, let's take a look at the member definitions of this object:

Public class javascriptserializer
{
// Field
Internal const int defamaxmaxjsonlength = 0x200000;
Internal const int defaultrecursionlimit = 100;
Internal const string servertypefieldname = "_ type ";

// Method
Static javascriptserializer ();
Public javascriptserializer ();
Public javascriptserializer (javascripttyperesolver resolver );
Public t converttotype (Object OBJ );
Public t deserialize (string input );
Public object deserializeobject (string input );
Public void registerconverters (ienumerable converters );
Public String serialize (Object OBJ );
Public void serialize (Object OBJ, stringbuilder output );

// Attributes
Public int maxjsonlength {Get; set ;}
Public int recursionlimit {Get; set ;}
Internal javascripttyperesolver typeresolver {Get ;}
}

Note that if the number of nested objects is greater than 100 defined in the recursionlimit attribute, the serialization process will fail. Obviously, if the serialized string length exceeds the value 0x200000 (decimal 2,097,152) defined in the maxjsonlength attribute, the serialization process will also fail.

In addition, the Code above shows that the object will be serialized as a stringbuilder object, and the corresponding string data will be returned. In fact, the main work is done in the private method serializevalue. Before discussing this method, we first notice that the javascriptserializer object uses the javascripttyperesolver object. This JavaScript parser converts string types to other types. This function is very important when serializing custom objects. It should also be noted that the __type attribute will be included in the JSON serialized text to identify the object type. Then, the client deserializes the JSON text into the original object form.

The javascripttyperesolver object includes two public methods. One is responsible for resolving the original type to the string type, and the other is responsible for parsing the string to the original type. The prototype of this class is defined as follows:

Public abstract class javascripttyperesolver
{
// Method
Protected javascripttyperesolver ();
Public abstract type resolvetype (string ID );
Public abstract string resolvetypeid (type );
}

Obviously, the javascripttyperesolver class above is an abstract base class. Therefore, it must be further derived and used by other objects, so that the corresponding parsing between the original type and the string can be achieved. Now, the object we can use is simpletyperesolver, And it exactly implements the method required above-use system. the type object parses the string description form and the original type object. See the following example:

Public override type resolvetype (string ID)
{
Return type. GetType (ID );
}

Public override string resolvetypeid (type)
{
If (type = NULL)
{
Throw new argumentnullexception ("type ");
}
Return type. assemblyqualifiedname;
}

Finally, the javascriptserializer object may also use the javascriptconverter object because the built-in serialization process Cannot serialize all available data types. In this case, a subclass can be derived from the abstract base class javascriptconverter object to implement sequence/deserialization of specific data types. You can use the registerconverters () method of the javascriptserializer object to register a converter object. This method stores all converter objects in a dictionary object. Transformer files of different data types are registered and stored in this dictionary object. In summary, this dictionary object is defined as some data types shown in table 1.

Table 1 -Summary of serializable Data Types
Raw Data Type Serialized form
Null or dbnull "Null"
String String with quotation marks
Char If it is '\ 0', it is converted to "null"; otherwise, it is serialized as a string with quotation marks.
Bool "True" or "false"
Datetime

Date object, which is expressed as "\/date (number of scales) \/" in JSON )\/". The number of scales is a positive or negative long value that indicates the number of scales that have passed since midnight, January 1, January 1, 1970 (milliseconds ).

The maximum supported date value is maxvalue.(December 31, 9999 11:59:59), and the supported minimum date value is minvalue(January 1, 0001 12:00:00 am ).

Guid "String Representation": SB. append (""). append (guid. tostring (). append (""");
Uri SB. append ("). append (URI. getcomponents (uricomponents. serializationinfostring, uriformat. uriescaped). append (""");
Double SB. append (double) O). tostring ("r", cultureinfo. invariantculture ));
Float SB. append (float) O). tostring ("r", cultureinfo. invariantculture ));
Primitive or decimal Iconvertible convertible = O as iconvertible;
SB. append (convertible. tostring (cultureinfo. invariantculture ));
Enum SB. append (INT) O );
Idictionary Convert to a JSON text string, for example:
{"Key1": value1, "key2": value2 ...}
Ienumerable Convert to a JSON text string, for example:
{"Key1": value1, "key2": value2 ...}

For custom objects, they can be serialized in a way similar to idictionary, but there are still some differences. If a javascripttyperesolver object is defined in advance, the object type will be converted into a string, so the object definition will include a String constant _ type, it is followed by a string that describes the object data type. All fields and attributes defined as public and without the metadata scriptignoreattribute attribute are included in the JSON object description of this object.

 

Iii. Sequence/deserialization examples

Now, let's use an example to analyze the serialization process. First, consider the customer object defined below:

Public Class Customer
{
Private string _ firstname;
Public String firstname
{
Get {return _ firstname ;}
Set {_ firstname = value ;}
}
Private string _ lastname;
Public String lastname
{
Get {return _ lastname ;}
Set {_ lastname = value ;}
}
Private string _ email;
Public String emailaddress
{
Get {return _ email ;}
Set {_ email = value ;}
}
Private phone _ phonenumber;
Public phone phonenumbers
{
Get {return _ phonenumber ;}
Set {_ phonenumber = value ;}
}

}< br> public class phone
{< br> private string _ homephone;
Public String homephone
{< br> get {return _ homephone ;}< br> set {_ homephone = value ;}
}< br> private string _ workphone;
Public String workphone
{< br> get {return _ workphone ;}
set {_ workphone = value ;}< BR >}

If this object is returned through a Web service method, the object will be automatically serialized in the invokemethod () method of the internal processor resthandler class. However, in the preceding example, we use these objects in the typical page. page_load () method of our web page. Therefore, we should create these objects and automatically serialize them using the javascriptserializer object discussed earlier. For example, consider the following code to serialize an object:

Javascriptserializer jsserializer = new
Javascriptserializer (New simpletyperesolver ());
Customer Cust = new customer ();
Cust. firstname = "Joe ";
Cust. emailaddress = "jknown@domain.com ";
Cust. phonenumbers = new phone ();
Cust. phonenumbers. homephone = "888-888-8888 ";
String serializedtext = jsserializer. serialize (Cust );

According to the previous analysis, the javascriptserializer object has been initialized using simpletyperesolver (simpletyperesolver is responsible for converting the object to be serialized into a string ). Next, let's take a look at the serialized JSON text:

{"_ Type": "customer, app_web_plrzlwbj,
Version = 0.0.0.0, culture = neutral,
Publickeytoken = NULL "," firstname ":" Joe "," lastname ": NULL,
"Emailaddress": jknown@domain.com,
"Phonenumbers": {"_ type": "phone, app_web_plrzlwbj, version = 0.0.0.0,
Culture = neutral, publickeytoken = NULL ",
"Homephone": "888-888-8888", "workphone": NULL }}

Note that the phonenumbers attribute belongs to the custom type-phone. Therefore, when serialized, the value of the phonenumbers attribute is itself a JSON object, which is exactly the serialized form of the phone object. Once again, the type mark is added for deserialization to ensure that the original object of the corresponding type is created.

Next, let's take a look at the deserialization process.

The deserialization process is implemented by using the javascriptobjectdeserializer object. When an object instance is created, the corresponding JSON text string is passed to the constructor of this class as a parameter. When the object instance is created, we can call the deserializeinternal () method. This method parses JSON serialized strings and creates corresponding primitive objects.

The above analyzes the internal implementation of deserialization. However, as a programmer using the javascriptserializer class, to implement deserialization of a json string, we only need to simply call the deserialize () method of the javascriptserializer object. The return value of this method corresponds to an instance of the original object, and the corresponding attributes are correctly assigned values. Let's consider the following code:

Customer Cust = jsserializer. deserialize (serializedtext );

Here, the content presentation of the variable Cust is no longer provided, and interested readers can track and analyze it automatically.

Iv. client-side javascriptserializer object

ASP. the Microsoft Ajax library in the net Ajax client framework also provides a sys. serialization. criptserializer object, so that it is convenient in non-Asp-based. ASP. NET platform.. Net Ajax programming JSON data encoding and decoding. This javascriptserializer object exposes two methods: serialize and deserialize.

The serialize method accepts parameters in the form of a JavaScript Object. This function returns a string describing JSON data, for example:

VaR man = {firstname: 'john', lastname: 'Mike '};

VaR S1 = SYS. serialization. javascriptserializer;

VaR JSON = s1.serialize (man );

Here, the variable JSON stores a string that corresponds to the JSON description of the object stored in the variable man.

The deserialize method executes the task opposite to the serialize method. It accepts a parameter in the form of a JSON string and returns the corresponding JavaScript Object, for example:

VaR man = serializer. deserialize (JSON );

Note that when using a JSON analyzer, you need to be careful with the processing method of date data because JavaScript does not directly support data in the date format. For more JSON operations on date-format data, refer to the examples provided on the official website.

 

V. Summary

Now you should have a basic understanding of the JSON serialization and deserialization processes in the ASP. NET Ajax framework and how to use the JSON serialization technology. In general, the process of JSON serialization or deserialization is relatively simple, especially when the client analyzes JSON text strings, which is simpler than the serialization analysis of XML data.

In ASP. NET Ajax programming, the form of data storage during the communication between the server and the client is a basic problem. In ASP. net Ajax server-side framework programming, you can use ASP. net Ajax core assembly system. web. the namespace system. web. script. the javascriptserializer class in serialization provides methods for JSON data serialization and deserialization. In ASP. NET Ajax-based client framework programming, You can implement JSON data serialization and deserialization Based on the SYS. serialization. javascriptserializer object provided in Microsoft Ajax library.

This article Reprinted from: http://tech.sina.com.cn/s/2008-04-11/15342133163.shtml

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.