Json and serialization summary, Json serialization Summary

Source: Internet
Author: User
Tags emit object serialization

Json and serialization summary, Json serialization Summary

I. Preface

When you encounter problems, you will often visit the garden. I wonder if you have ever encountered problems, or you may see solutions to problems in the garden. After a while, you may be wrestling, haha... please do not try it out. The younger brother is not very good at remembering it. If I write a summary of the problem or a certain knowledge point, the problem will be more profound and I will be more familiar with what I wrote. Reading articles written by others is quite an envy. For personal reasons such as not dare to write or be lazy, I 've been stuck on a treadmill, and I 've never been a huge step forward, but I just wanted to write it. Today, I try to change myself a little bit. From the summary of some of my knowledge, if something is wrong or wrong during the process, please let me know more ....... the topic on the first day is Json and serialization.

Ii. json and serialization

First, let's get a preliminary understanding of json and serialization. Previously, the interviewer also asked related questions, what is json and several display methods? What are the serialization tools you usually use, what are its advantages? The following is a simple drawing to illustrate the understanding and introduction of json and serialization:

Iii. code example

We often use several serialized objects: DataContractJsonSerializer, JavaScriptSerializer, and Json. NET (Newtonsoft ). Let's talk little nonsense. Let's go to the code. Here we will go to the stage one by one:

Leading Role: JavaScriptSerializer

(1) first, add the reference System. Web. Extensions.

Note: The JavaScriptSerializer application json.net uses serialization and deserialization to provide serialization and deserialization for Ajax-enabled applications.

Namespace:System. Web. Script. Serialization
Assembly:System. Web. Extensions (located in System. Web. Extensions. dll)

 

Code instance

 

Static void Main (string [] args) {List <User> userList = new List <User> () {new User {Name = "handsome guy", Age = 13, gender = "male"}, new User {Name = "", Age = 13, Gender = "female" }}; // JavaScriptSerializer serializes var javaScrittLizer = new JavaScriptSerializer (). serialize (userList); Console. writeLine ("serialization:" + javaScrittLizer); // JavaScriptSerializer deserialization string strJson = "{\" Name \ ": \" Michael \ ", \" Age \ ": 28, \ "Gender \": \ "female \"} "; var deserialize = new JavaScriptSerializer (). deserialize <User> (strJson); Console. writeLine ("deserialization: Name:" + deserialize. name + "Age:" + deserialize. age); Console. readKey () ;}public class User {public string Name {get; set ;}public int Age {get; set ;}public string Gender {get; set ;}}

 

Result:

 

 

Second main character: Json. NET

(1) first, add the installation package in Negut.

(2) Add 2. Add Newtonsoft. Json and Newtonsoft. Json. Linq references

(3) Newtonsoft. Json we mainly use three methods to meet our daily development requirements:Serialization: SerializeObject (),Deserialization: DeserializeObject ()

There is another entity type that may not have a corresponding one (or you do not want to add the corresponding entity class). At this time, you can use the anonymous object resolution method.DeserializeAnonymousType ()The corresponding code is as follows:

(4) Conclusion: Newtonsoft. Json adopts Emit Cache Optimization, and the running efficiency is close to the efficiency of manual code generated by fastCSharp. It is really good. We will show you the test data later,

// 1. add Json.net // 2 from NuGet first. add Newtonsoft. json and Newtonsoft. json. reference static void Main (string [] args) {List <User> userList = new List <User> () {new User {Name = "handsome guy", Age = 13, gender = "male"}, new User {Name = "", Age = 13, Gender = "female" }}; // serialize var userserializer = JsonConvert. serializeObject (userList); Console. writeLine ("serialization:" + userserializer); // deserialization string strJson = "{\" Name \ ": \" Zhang San \ ", \" Age \ ": 28, \ "Gender \": \ "female \"} "; User user = JsonConvert. deserializeObject <User> (strJson); Console. writeLine ("deserialization: Name: {0}, age: {1}, Gender: {2}", user. name, user. age, user. gender); // anonymous deserialization // there may be no corresponding entity type (or you do not want to add the corresponding entity class). In this case, you can use the anonymous Object Parsing Method DeserializeAnonymousType (), which is convenient and fast, the corresponding code is as follows: var tempEntity = new {Name = "0", Gender = string. empty}; tempEntity = JsonConvert. deserializeAnonymousType ("{\" Name \ ": \" handsome guy \ ", \" Gender \ ": \" male \ "}", tempEntity); Console. writeLine ("anonymous serialization: Name:" + tempEntity. name + ", Gender:" + tempEntity. gender); Console. readKey () ;}public class User {public string Name {get; set ;}public int Age {get; set ;}public string Gender {get; set ;}}

Effect display:

 

Third Leading Role: DataContractJsonSerializer

(1) the old rule must be referenced: System. ServiceModel. Web and System. Runtime. Serialization.

(2) programmers should simply click and directly go to the Code:

There was an episode during the DataContractJsonSerializer demo test:

(1) During deserialization, The Deault adopts ANSI encoding and does not compile and report errors, but does not display deserialization results. Please be careful because UTF8 encoding is used here.

(2) If the [Serializable] [DataContract] attribute is not added to the User class, an error will be reported directly. For the error, I also gave Baidu relevant information and explained it in the code, if this parameter is not added, the following string is displayed:<Name> k_BackingField

You can try it. The code and the following summary will give you the answer.

Still do not understand can access: https://msdn.microsoft.com/zh-cn/library/bb412179.aspx

/// <Summary> /// DataContractJsonSerializer serialization case /// add reference: System. serviceModel. web and System. runtime. serialization // </summary> // <param name = "args"> </param> static void Main (string [] args) {List <User> userList = new List <User> () {new User {Name = "handsome guy", Age = 13, Gender = "male "}, new User {Name = "", Age = 13, Gender = "" }}; // serialize DataContractJsonSerializer serializer = new DataContractJsonSerializer (ty Peof (List <User>); using (MemoryStream stream = new MemoryStream () {serializer. writeObject (stream, userList); var dataString = Encoding. UTF8.GetString (stream. toArray (); Console. writeLine ("serialization:" + dataString);} // serialize string strJson = "{\" Name \ ": \" Zhang San \ ", \" Age \ ": 28, \ "Gender \": \ "\"} "; DataContractJsonSerializer desserializer = new DataContractJsonSerializer (typeof (User); var mStream = new MemoryS Tream (Encoding. default. getBytes (strJson); User desUser = (User) desserializer. readObject (mStream); Console. writeLine ("deserialization:" + "name:" + desUser. name + ", age:" + desUser. age); Console. readKey ();} // Serializable attribute. // This attribute must be set to [System. serializable] label, // This label indicates that a class can be serialized. It is easy to transmit and save this label in the network. This label is a feature that can be serialized, indicating that this class can be serialized. /// The DataContract service contract defines the remote access object and the method that can be called. The data contract is the custom data type to be transferred between the server and the client. /// Once a data type is declared as DataContract, this type can be serialized and transmitted between the server and the client, as shown below. [Serializable] // indicates that a class can serialize [DataContract] public class User {[DataMember] public string Name {get; set;} [DataMember] public int Age {get; set ;}[ DataMember] public string Gender {get; set ;}}

Test results:

 

I also checked a lot of information on the Internet. They compared the performance of the three comparisons:It is best to use a third party: Json.net ,(Personal recommendations)

Link: http://json.codeplex.com/can also download the source code in it, research, hey

As the saying goes, it's not a book, it's just a reality. Let's examine it. practice is the only criterion for testing truth. We can't hear it, Hahahaha ..... In this statement, I can only verify it, not challenge it, haha

Computer Configuration reasons, some things, no display effect, or other reasons, God knows, please advise more .....

Static void Main (string [] args) {User user = new User {Name = "handsome guy", Age = 20, Gender = "South "}; list <User> userList = new List <User> (); for (int I = 0; I <5000; I ++) {userList. add (user) ;}stopwatch sw = new Stopwatch (); Stopwatch sw1 = new Stopwatch (); Stopwatch sw2 = new Stopwatch (); // serialize criptserializer to serialize sw. start (); // var javaScrittLizer = new JavaScriptSerializer (). serialize (userList); Console. writeLine ("JavaScriptSerializer serialization:" + sw. elapsed); // JsonConvert serializes sw1.Start (); var userserializer = JsonConvert. serializeObject (userList); Console. writeLine ("JsonConvert serialization:" + sw1.Elapsed); // DataContractJsonSerializer serialization sw2.Start (); DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (List <User> )); using (MemoryStream stream = new MemoryStream () {serializer. writeObject (stream, userList); var dataString = Encoding. UTF8.GetString (stream. toArray (); Console. writeLine ("DataContractJsonSerializer serialization:" + sw2.Elapsed);} Console. readKey ();} [Serializable] // indicates that a class can be serialized with [DataContract] public class User {[DataMember] public string Name {get; set ;} [DataMember] public int Age {get; set;} [DataMember] public string Gender {get; set ;}}

 

 

 

Summary:

Newtonsoft. Json adopts Emit Cache Optimization, and the running efficiency is close to the efficiency of manual code generated by fastCSharp. It is really good.
DataContractJsonSerializer in. NET Framework 3.5 was introduced, mainly because of the introduction of WCF and added the basic method for Object serialization. Microsoft also tagged JavaScriptSerializer with obsolete (obsolete) labels, A warning will appear during compilation.
In. NET Framework 3.5 SP1, Microsoft removed the "obsolete" label of JavaScriptSerializer.
Using Reflector to compare the internal implementations of these two classes, we found that DataContractJsonSerializer performs more rigorous checks during Object serialization. If you are interested, you can go to System. runtime. serialization. the core method InternalWriteObjectContent under Json is used to see its implementation.
While in. the automatic attribute introduced by NET Framework 3.5 is actually a syntactic sugar. the compiler will still generate a private field of the int type <Name> k_BackingField as the backend field of this attribute, the internal method is the same as the previous get/set method.
Therefore, when DataContractJsonSerializer is directly used for serialization, k_BackingField generated by the compiler is taken out.
The implementation of JavaScriptSerializer is very simple. attributes and attribute values are stored in Dictionary respectively, and then strings are spliced and returned, therefore, the class definition is almost not checked and the support for complex classes is not very good.

I personally understand all of the above. If something is wrong, please kindly advise me more... hahaha. The first article has finally been written. I am sorry for the bad things.

 

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.