Internal implementation differences between DataContractJsonSerializer and JavaScriptSerializer

Source: Internet
Author: User
Tags definition class definition json serialization

A primer on the problem

First look at the introduction to the problem.

Defines a class that has the serializable attribute, and that the definition of a property is not implemented using an automatic property.

[Serializable]
 public class The Users
 {public
     int UserID {get; set;}
     
     public string UserName {get; set;}
     
     public string UserEmail {get; set;}
     
     private string _testproperty;
     public string TestProperty
     {get
         {return _testproperty;}
         set {_testproperty = value;}
     }
 }

The examples of this object are then serialized using DataContractJsonSerializer and JavaScriptSerializer, respectively.

The result of using DataContractJsonSerializer serialization.

{"_testproperty": "TestPropertyValue", "<useremail>k__backingfield": "Parry@cnblogs.com",
"<userid>k__backingfield": 1, "<username>k__backingfield": "Parry"}

The result of using JavaScriptSerializer serialization.

{"UserID": 1, "UserName": "Parry", "UserEmail": "Parry@cnblogs.com", "TestProperty": "TestPropertyValue"}

Implementation differences between DataContractJsonSerializer and JavaScriptSerializer

DataContractJsonSerializer was introduced in the. NET Framework 3.5, and the basic method of serializing this object was added primarily because of the introduction of WCF, And Microsoft has also put JavaScriptSerializer on the outdated (obsolete) label, and there will be warnings at compile time.

In the. NET Framework 3.5 SP1, Microsoft has removed JavaScriptSerializer's "outdated" label.

Using reflector to compare the internal implementation discovery of these two classes, the DataContractJsonSerializer is examined more rigorously in the serialization of objects, Interested can go to System.Runtime.Serialization.Json the core method below internalwriteobjectcontent to see its implementation.

The automatic properties introduced in the. NET Framework 3.5 are actually syntax sugars, and the compiler generates a <name>k_backingfield private field of type int as the back-end field of this property, and the internal or previous get/ The same as the set method.

Therefore, the compiler-generated K_backingfield is brought out directly using DataContractJsonSerializer for serialization.

The implementation of the JavaScriptSerializer is very simple, the property name and attribute values are stored in the dictionary, and then string concatenation return, so the class definition is almost not checked and support for complex classes is not very good.

The following is the implementation of the core method Serializevalue inside the JavaScriptSerializer.

private void Serializevalue (Object o, StringBuilder sb, int depth, Hashtable objectsinuse, Serializationformat Serializa Tionformat, MemberInfo CurrentMember = null) {if (++depth > _recursionlimit) {throw new argumentexcept 
     Ion (atlasweb.json_depthlimitexceeded);
     }//Check Whether a custom converter is available to this type.
     JavaScriptConverter converter = null; if (o!= null && converterexistsfortype (O.gettype (), out Converter)) {idictionary<string, object> Dict = converter. 
     
         Serialize (o, this); 
             if (typeresolver!= null) {string typestring = Typeresolver.resolvetypeid (O.gettype ()); 
             if (typestring!= null) {Dict[servertypefieldname] = typestring; } sb. 
         Append (Serialize (Dict, Serializationformat));
     Return Serializevalueinternal (o, SB, depth, Objectsinuse, Serializationformat, CurrentmembER); }

Solving method

If you must use DataContractJsonSerializer, only if you add the [DataContract] property to the class and add [DataMember] to the attribute that needs to be serialized, Use DataContractJsonSerializer to generate clean, neat JSON data.

And when we use a class definition that cannot be modified, such as the user class definition above, we do not have permission to modify its definition, 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 supporting functionality and efficiency, Look at it in contrast to the use of DataContractJsonSerializer and JavaScriptSerializer.

So you need to take a little notice of the differences in these three JSON serialization methods and choose the right components flexibly according to your needs.

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.