Json serialization, deserialization, and Json serialization

Source: Internet
Author: User
Tags lol account

Json serialization, deserialization, and Json serialization

Think about one day, when you were watching the LOL strategy, the system suddenly crashed, and then the browser showed up a complicated LOL account and password. You must be thinking, "Oh, I am going to make a fortune this time, maybe there is an extraordinary number or king number in it. I have to remember it all." But then you are shocked. So many accounts and passwords are all written in Json. When should I remember to copy and paste them one by one... If I am by your side at this time, I will certainly help you, on the premise that you need to give me a few Kingdom accounts...

  

 

Let's get down to the truth.

Although the above example is a bit unrealistic, I 'd like to explain a problem to you. If you want to parse Json or XML,Please do not use the string Retrieval Method !!!

Before explaining how to parse Json and XML, let's clarify two concepts:SerializationAndDeserialization.

"Serialization, that is, Serialization, isObject status informationToCan be stored or transmitted.」

"Deserialization, that is, Deserialization, isSequences that can be stored or transmittedTransform to an objectStatus information.」

From the above definition, we can draw two conclusions:

① These two processes are inverse processes;

② Whether serialized or deserialized, the object state information is consistent with a sequence.

Next, let's take a look at how to serialize and deserialize Json and XML in C.

  

Json serialization and deserialization

① Use the Newtonsoft. Json Library

First, let's look at a piece of code:

1 public void JsonDeserialize (string jsonString) 2 {3 // deserialization operation 4 JObject jObject = JsonConvert. deserializeObject (jsonString) as JObject; 5 // clear listBox result 6 listBoxResult. items. clear (); 7 // display the parsed data to 8 listBoxResult in listBox. items. add ("Name:" + jObject ["name"]? "Null"); 9 listBoxResult. Items. Add ("Doing:" + jObject ["doing"]? "Null"); 10 listBoxResult. Items. Add ("HandleContent:" + jObject ["handleContent"]? "Null"); 11 listBoxResult. Items. Add ("DateTime:" + jObject ["dateTime"]? "Null"); 12}

The above method is used to receive a Json sequence as a parameter. After deserialization, all the field values are output to ListBox. Below is a simple test:

  

We can see that only one line of code is used, and the Json content is obtained according to all the fields. Let's take a good look at the usage of the Newtonsoft. Json library.

Newtonsoft. json is. NET platform, a popular and high-performance Json serialization and deserialization open-source library, provides many classes and methods for serialization and deserialization of Json, in addition, it also provides the ability to operate Json with Linq and convert Json into XML. Compared with the traditional DataContractJsonSerializer class for serialization and deserialization, it is easier to use and more efficient. This article only describes the important JsonConvert classes and several common types. For more information, visit the homepage of Json. NET.

Before introducing the usage, let's talk about the introduction of Newtonsoft. Json. dll. Starting from VS2013, ASP. NET projects all come with Newtonsoft. json. dll, which can be used directly. If other versions or projects do not exist, you can go to its official homepage and find the address hosted by Github to go to and download. The following describes how to reference the dynamic link library,

① Click "project"> "add reference" in the menu bar, or find the project in Solution Explorer, right-click "reference property", and click "add reference". The window opens.

After this window is opened, if Newtonsoft is added for the first time. json. dll. Find the Browse button in the lower-right corner and select Newtonsoft. json. dll; if you have previously added this library, you can click the Browse menu on the left and click the nearest one. The information of the previously added library is displayed on the right side, and the required library is checked, click OK in the lower right corner.

  

  

The Dynamic Link Library has not been added yet. To use the classes and methods in the dynamic link library, you need to introduce the corresponding namespace (if you do not want to write a long string of namespaces for every object defined ), the namespace used in this article isNewtonsoft. JsonAndNewtonsoft. Json. Linq.

  

After completing these two steps, you can easily start parsing our great Json.

Now, first introduce the important classes in this library,JsonConvert. JsonConvert is a very practical tool class. It provides the DeserializeObject method and DeserializeObject Method for deserialization, as well as the SerializeObject Method for serialization. Because these methods are static methods, you do not need to create a JsonConvert object and use them properly (in fact, JsonConvert is a static class and cannot be instantiated at all ).

In the first demo, we used the JsonConvert. DeserializeObject method, which is the most primitive Json deserialization method. It receives parameters of the string type and returns objects of the object type. Then you may ask, what type of objects does it return ??? To obtain the information of this object, you must forcibly convert it into a specific derived class. Then, we can use the GetType method to find out.

1 private void btnDeserialize_Click(object sender, EventArgs e)2 {3     //JsonDeserialize(textBox1.Text);4     var secretObject = JsonConvert.DeserializeObject(textBox1.Text);5     MessageBox.Show(secretObject.GetType().ToString());6 }

We first parse the input Json sequence in the method corresponding to the Click Event of a button, because we are not sure about JsonConvert. the DeserializeObject method returns objects. Therefore, we first use an implicit type object to reference the results returned by this method, and then call its GetType method to obtain the metadata of the object type, finally, the complete type name of the object is displayed in the dialog box. Run this code and you will see the following results:

  

Maybe at this time, there may be another 10 thousand grass-mud horses in your heart? I haven't figured out the usage of the JsonConvert class yet. Why is another Strange Class running out ?"

But it doesn't matter. Next I will explain the mysteries one by one.

In the Newtonsoft. Json. Linq namespace, some classes are defined to represent different forms of Json strings, including JObject, JProperty, JToken, JArray, JValue, and JContainer.

Among these classes, JToken acts as a benchmark. It is an abstract class and implements the IJEnumerable <T> interface, the IJEnumerable <T> interface inherits from the IEnumerable <T> interface, which means that all classes that inherit the JToken can be traversed using the foreach statement. The classes to be introduced next are as follows, all are derived from JToken. In addition, JToken defines attributes that are frequently used for First, Last, Parent, Root, Item, Previous, And Next traversal. Therefore, when using these classes, traversal and searching for specific classes are very simple. It's time to talk about JObject. This is a derived class of JToken. It also implements the JContainer interface, ICollection <T>, IKeyValuePair <T>, this means that JObject can store multiple objects that inherit the JToken type, traverse them, and use keys to obtain the corresponding values. Maybe you still don't know what these functions are, let's take a look at the basic structure of Json:

In general, the content enclosed by braces can be regarded as a whole (an object), while the content enclosed by braces can be considered as a group of content (an array ), in a complex Json structure, the value of a key in the braces can be embedded in a braces, representing that the attribute value is another Json object, similarly, the value of a key in a braces can be embedded with a bracket, which indicates that the attribute value is an array, such

1 // For This Json type, it can be viewed as an object that contains the name, doing, handleContent, and dateTime attributes. 2 {3 "name ":". NET Coder ", 4" doing ":" Deserialization ", 5" handleContent ":" Json ", 6" dateTime ": "12:12:12" 7} 8 9 // For This Json, it can be regarded as an array object, which contains two objects. 10 [11 {12 "name ":". NET Coder ", 13" doing ":" Deserialization ", 14" handleContent ":" Json ", 15" dateTime ":" 12:12:12 "16 }, 17 {18 "name": "Java Coder", 19 "doing": "Deserialization", 20 "handleContent": "Json", 21 "dateTime ": "2017-09-22 21:21:21" 22} 23]

In the previous example, we used the GetType Method to Determine the type actually returned after deserialization; next, we will put the Json sequences of the above two different structures into the program for parsing, to see if the obtained objects are all JObject.

  

The JObject type object is obtained successfully.

  

This time we actually got JArray ?!

Now we may understand that JObject is used to representComplete Json object structureWhile JArray is used to representJson ArrayContains one or more Json objects.

After obtaining the JObject object, we can use the attribute name (key) to obtain the corresponding attribute value, or use the attributes such as Next and Previous to access the attributes of JObject one by one.

After obtaining the JArray object, we can use the for or foreach statement to traverse the elements in the object, then, access the attribute values of a certain attribute of the current element based on a property name, such as Next and Previous.

So what is the role of the JProperty and JValue types?

We can debug the program and observe the structure in the JObject object,

When we use foreach to traverse the attributes inside JObject, we can see that the First attribute points to the First attribute of JObject, and its type is JProperty, so we can know that, the JProperty class is used to describe a property in a Json object and contains a member variable of KeyValuePair <string, JToken>. It is used to store the key-value pairs of this Json property, this value is actually a variable of the JValue type.

  

So far, we have mastered the DeserializeObject method usage, but it is obvious that this method is too troublesome to parse Json data, we need to obtain the attributes of all Json objects one by one before we can get the values. Is there a more general approach?

Yes! Yes! Yes! The important thing is said three times.

The next turn is the DeserializeObject <T> method. This is a generic method. After specifying the T type and passing in the Json string as the parameter, this method completes deserialization and returns a T-type object. So what type should we specify for this method? This type needs to be designed based on the hierarchical relationship of Json data. If you are using it for the first time and do not know how to design it, let's let VS help us design it, next we will introduce a magic function, VS's automatic class creation function:

If we need to deserialize the Json sequence but do not know how to design the class, we can copy the Json sequence first,

1 {2     "name":".NET Coder",   3     "doing":"Serialization",4     "handleContent":"Json",5     "dateTime":"2017-09-11 12:12:12"6 }

Open VS, choose Edit> paste on the menu bar, and click paste Json as a class. The following result is displayed,

In the original blank space, a class definition suddenly emerged (if Json has multiple levels, VS will generate multiple classes). This class clearly reflects the Json structure, in this case, we only need to use the automatically generated class in the method:

  

   

We modified the JsonDeserialize method and used the class generated by VS. We can see that we no longer need to obtain the attribute value based on the attribute name, you don't have to worry about missing attributes or incorrect attribute names. You just need to add a point after the object. All attributes of the object will appear in the selection list. Did you suddenly feel that it was easy and bright? However, this practice hides a small problem because VS defines attributes based on the original Json attribute name, which requires that the Json attribute name follow the identifier definition rules of C, then, in fact, there may be attribute names that do not comply with the C # identifier definition specification in Json, which is correct, as shown in the following Json:

1 {2     "name":"money",   3     "price":"66.6",4     "int":"64",5     "a-b":"c-d",6     "@#$":"sdfsdf"7 }

It can be seen that, although VS will use _ to replace invalid strings and generate attribute names according to the specifications, this attribute name has lost its meaning, we cannot know what this attribute represents. To solve this problem, we can use the C # annotation to define the attributes of this class.Data protocols.

  

 

DataContract and DataMember annotations come from namespacesSystem. Runtime. SerializationThe Dynamic Linked Library project of this namespace is not introduced by default. You need to introduce it manually. We only need to introduce Newtonsoft according to the above. json. it is good to introduce the dll method, but note that the System. runtime. the dynamic link library of Serialization is provided in the VS Assembly. On the Add reference page, click the Assembly and find System in the list on the right. runtime. select the Serialization check box and click OK in the lower right corner.

After completing these steps, we can transform the Json object class and add data protocols to it. What is a data protocol? That is, the data sender and receiver do not need to use the same type, but only need to follow the data protocol. To enable this class to add data protocols, you must add[DataContract]Annotation, indicating that the attribute of this class uses the data protocol and allows serialization of this class,If this annotation is not added, the [DataMember] annotation cannot be used.. Add[DataContract]After annotation, we can add the [DataMember] Annotation on the corresponding attribute. This annotation has four parameters:

Parameter Name Function
Name Identifies the Json property name corresponding to this property
Order Identifies the serialization and deserialization order of this attribute.
IsRequired Indicates whether the attribute must exist during reading or deserialization. The type is bool.
Emitdefavalue Value Indicates whether the default value of this attribute is used for serialization during serialization.

 

We use the Name parameter to set the Json attribute Name corresponding to each attribute, which enhances the readability of the class in the program without causing any trouble in the serialization and deserialization processes. Next, rewrite the JsonDeserialize method:

  

Test successful !!!

In addition, to avoid creating too many entity classes when we need to deserialize many simple Json classes, we can use dynamic types instead of custom object classes, here we rewrite the above example and use the dynamic type to implement the corresponding functions:

  

 

In this example, I didn't define a new class, but used a dynamic type. This type of object has a feature:Runtime check. When using such an object, we should note that the compiler will not check whether it is using its attributes or calling its methods, in other words, we must ensure that the attribute name or method name is not written incorrectly. Otherwise, the expression is null or an exception occurs.

  

If the call does not exist, Null is returned.

 

  

An exception is thrown when a nonexistent method is called.

 

  

If no error exists, it runs successfully!

  

The deserialization introduction has come to an end. Next we will talk about using the JsonConvert. SerializeObject method to complete the serialization operation.

The purpose of the above operations is to parse the Json string so that we can easily obtain the information. But if we are not the receiver of the information but the sender, how should we construct the Json string? Obviously, the String concatenation method is unavailable, Which is inefficient and difficult to troubleshoot. So today we will useOne line of codeTo complete this task.

  

  

 

That's right. There's only one line of code !!!

 

  

  

Let's see if a line of code instantly changes a living object into a Json string !!!

  

  ② Use DataContractJsonSerializer class

In fact, I don't want to explain this category. The first use process is very troublesome, the second is inefficient, and it will not be used in actual work. But from the perspective of learning, we still need to understand the existence of this category, in addition, this class serialization and deserialization process are similar to XML serialization and deserialization, so it is necessary to let everyone know.

If you don't talk about other things here, simply add the Code:

DataContractJsonSerializer serialization

1 public void OldJsonSerialize () 2 {3 DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (HandleObject); 4 // create entity Class 5 HandleObject jObject = new HandleObject () {6 Name = ". NET Coder ", 7 Doing =" Serialization ", 8 HandleContent =" Json ", 9 DateTime = DateTime. now. toString ("yyyy-MM-ss") 10}; 11 // create a memory stream for storing the serialized content 12 MemoryStream MS = new MemoryStream (); 13 // serialize the object and save it to the memory stream 14 serializer. writeObject (MS, jObject); 15 // convert the content of the memory stream into a string and output it to the text box 16 textBox1.Text = Encoding. UTF8.GetString (ms. toArray (); 17}

 

  DataContractJsonSerializer deserialization

1 public void OldJsonDeserialize () 2 {3 DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (HandleObject); 4 // converts a Json string to a byte array of 5 bytes [] content = Encoding. UTF8.GetBytes (textBox1.Text); 6 // initialize a memory stream object with a byte array 7 MemoryStream MS = new MemoryStream (content); 8 // complete deserialization operation 9 HandleObject handleObject = serializer. readObject (MS) as HandleObject; 10 // display parsed data to listBox 11 listBoxRe Sult. Items. Add ("Name:" + handleObject. Name ?? "Null"); 12 listBoxResult. Items. Add ("Doing:" + handleObject. Doing ?? "Null"); 13 listBoxResult. Items. Add ("HandleContent:" + handleObject. HandleContent ?? "Null"); 14 listBoxResult. Items. Add ("DateTime:" + (handleObject. DateTime. ToString ()?? "Null"); 15}

 

The biggest difference between the DataContractJsonSerializer class and the JsonConvert class is that the DataContractJsonSerializer class exposes the details of the operation stream and needs to be completed by the user. It is much more difficult to directly use strings than JsonConvert.

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.