DataContractJsonSerializer and JavaScriptSerializer Internal implementation differences

Source: Internet
Author: User
Tags class definition object serialization

Define a class such as the following, which has the Serializable property, and the definition of a property is not implemented using automatic attributes.

[Serializable] Public classUsers { Public intUserID {Get;Set; }  Public stringUserName {Get;Set; }  Public stringUserEmail {Get;Set; } Private string_testproperty;  Public stringTestProperty {Get{return_testproperty;} Set{_testproperty =value;} } }


Examples of this object are then serialized using DataContractJsonSerializer and JavaScriptSerializer, respectively.
Use DataContractJsonSerializer to serialize the result.

{
"_testproperty":"TestPropertyValue",
"<useremail>k__backingfield":"[email protected]","<userid>k__backingfield":1,
"<username>k__backingfield":"Parry"
}

Use JavaScriptSerializer to serialize the result.

 {

" userid ": 1 ,

" username : " parry ,

" useremail : " [email protected] ,

" testproperty ": " testpropertyvalue "

}

DataContractJsonSerializer and JavaScriptSerializer differences in implementation
The DataContractJsonSerializer was introduced in the. NET Framework 3.5, mainly because of the introduction of WCF and added the basic method of this object serialization. And Microsoft also put JavaScriptSerializer on the outdated (obsolete) label, compile will have a warning appears.
In the. NET Framework 3.5 SP1, the "obsolete" label for JavaScriptSerializer is removed.
Using reflector to compare the internal implementations of these two classes, the DataContractJsonSerializer is examined more rigorously when the object is serialized, Interested can go to System.Runtime.Serialization.Json the following core method Internalwriteobjectcontent to see its implementation.
The automatic attribute introduced in the. NET Framework 3.5 is actually a syntactic sugar, and the compiler generates a private field of <name>k_backingfield of type int as the back-end field of this property, internally or in the previous get/ Set method.
So when serializing directly using DataContractJsonSerializer, there is a compiler-generated k_backingfield out.
The implementation of JavaScriptSerializer is very simple, the property name and property values are stored in the dictionary, and then string concatenation back, so the class is almost not checked and support for complex classes is not good.
The following is the implementation of the core method Serializevalue inside JavaScriptSerializer.

Private voidSerializevalue (ObjectO, StringBuilder SB,intdepth, Hashtable objectsinuse, Serializationformat serializationformat, MemberInfo CurrentMember=NULL) {     if(++depth >_recursionlimit) {         Throw NewArgumentException (atlasweb.json_depthlimitexceeded); }     //Check Whether a custom converter is available for the This type.JavaScriptConverter converter =NULL; if(O! =NULL&& Converterexistsfortype (O.gettype (), outConverter)) {IDictionary<string,Object> dict = Converter. Serialize (O, This); if(Typeresolver! =NULL) {             stringTypestring =Typeresolver.resolvetypeid (O.gettype ()); if(Typestring! =NULL) {Dict[servertypefieldname]=typestring; }} sb.         Append (Serialize (Dict, Serializationformat)); return; } serializevalueinternal (o, SB, depth, Objectsinuse, Serializationformat, CurrentMember); }


Workaround:

If you must use DataContractJsonSerializer, only if you add the [DataContract] property to the class, and you add [DataMember] to the property that requires serialization, Use DataContractJsonSerializer to generate clean, uncluttered JSON data.
And when we use some class definitions that cannot be modified, such as the users class definition above, we do not have permission to modify their definitions, then we can use JavaScriptSerializer to do JSON serialization.
Of course, third-party json.net (Newtonsoft.json) is also achievable, and is often a better choice in terms of the functionality and efficiency of support, See how it compares to DataContractJsonSerializer and JavaScriptSerializer here.
So you need to pay a little attention to the differences in the three JSON serialization methods, and choose the right components flexibly to your needs.

DataContractJsonSerializer and JavaScriptSerializer Internal implementation differences

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.