In C #, several methods of Json serialization and deserialization are summarized,
In this article, we will learn how to use C # to serialize data in Json format and deserialize Json data to objects.
JSON (JavaScript Object Notation) is a lightweight data-interchange format. it is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language independent.
Json (javascript Object Representation Method) is a lightweight data exchange format. It can be easily read and written, and can be easily converted and generated by computers, it is completely independent from the language.
Json supports the following two data structures:
- A set of key-value pairs-these data structures are supported in different programming languages;
- A set of ordered list type values, including arrays, sets, vectors, or sequences.
Json has the following forms:
1. Object
An unordered "key/value", an object in curly brackets"{Start with, and end with curly braces "}". After each "key", there is a colon and multiple key-value pairs are separated by commas. For example:
Var user = {"name": "Manas", "gender": "Male", "birthday": "1987-8-8 "}
2. Array
Sets the order of values. An array starts with brackets "[" and ends with brackets "]", and all values are separated by commas. For example:
Var userlist = [{"user": {"name": "Manas", "gender": "Male", "birthday": "1987-8-8 "}},
{"User": {"name": "Mohapatra", "Male": "Female", "birthday": "1987-7-7"}]
3. String
Any number of Unicode characters are marked with quotation marks and separated by a backslash. For example:
Var userlist = "{\" ID \ ": 1, \" Name \ ": \" Manas \ ", \" Address \ ": \" India \"}"
Now, after introducing JSON, there are three methods for pre-serialization and deserialization:
1. Use the JavaScriptSerializer class
2. Use DataContractJsonSerializer class
3. Use the JSON. NET class library
Let's take a look at how to useDataContractJsonSerializer
The DataContractJsonSerializer class helps us serialize and deserialize Json, which is in the System. Runtime. Serialization. Json namespace under the assembly System. Runtime. Serialization. dll.
First, here, I create a console program and create a class Student.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Runtime.Serialization;namespace JsonSerializerAndDeSerializer{ [DataContract] public class Student { [DataMember] public int ID { get; set; } [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } [DataMember] public string Sex { get; set; } }}
Note: The contract [DataMember] and [DataContract] in the Student Entity above must be added for the serialization and deserialization of DataContractJsonSerializer. It is optional for the other two methods.
Code of our program:
You must first reference the Assembly and introduce the namespace.
// Namespaces to be introduced using DataContractJsonSerializer. In System. Runtime. Serialization. dll. using System. Runtime. Serialization. Json; // namespaces ;//--------------------------------------------------------------------------------------------
# Region 1. dataContractJsonSerializer serialization and deserialization Student stu = new Student () {ID = 1, Name = "Cao", Sex = "male", Age = 1000 }; // serialize DataContractJsonSerializer js = new DataContractJsonSerializer (typeof (Student); MemoryStream msObj = new MemoryStream (); // write serialized Json format data to js in the stream. writeObject (msObj, stu); msObj. position = 0; // read StreamReader sr = new StreamReader (msObj, Encoding. UTF8); string json = sr. readToEnd (); sr. close (); msObj. close (); Console. writeLine (json); // deserialize string toDes = json; // string to = "{\" ID \ ": \" 1 \ ", \" Name \": \ "Cao \", \ "Sex \": \ "man \", \ "Age \": \ "1230 \"}"; using (var MS = new MemoryStream (Encoding. unicode. getBytes (toDes) {DataContractJsonSerializer deseralizer = new DataContractJsonSerializer (typeof (Student); Student model = (Student) deseralizer. readObject (MS); // deserialize the ReadObject Console. writeLine ("ID =" + model. ID); Console. writeLine ("Name =" + model. name); Console. writeLine ("Age =" + model. age); Console. writeLine ("Sex =" + model. sex);} Console. readKey (); # endregion
The result is as follows:
Let's take a look at the use of JavaScriptJsonSerializer:
JavaScriptSerializer is a class which helps to serialize and deserialize JSON. it is present in namespace System. web. script. serialization which is available in assembly System. web. extensions. dll. to serialize. net object to JSON string use Serialize method. it's possible to deserialize JSON string. net object using Deserialize <T> or DeserializeObject methods. let's see how to implement serialization and deserialization using JavaScriptSerializer.
Reference
// Configure // The namespace to be introduced using the JavaScriptSerializer method, which is in the assembly System. Web. Extensions. dll. using System. Web. Script. Serialization; // configure ;//----------------------------------------------------------------------------------------
# Region 2. javaScriptSerializer serialization and deserialization Student stu = new Student () {ID = 1, Name = "Guan Yu", Age = 2000, Sex = "male "}; javaScriptSerializer js = new JavaScriptSerializer (); string jsonData = js. serialize (stu); // Serialize Console. writeLine (jsonData); // deserialization Method 1: string desJson = jsonData; // Student model = js. deserialize <Student> (desJson); // deserialization // string message = string. format ("ID = {0}, Name = {1}, Age = {2}, Sex = {3}", model. ID, model. name, model. age, model. sex); // Console. writeLine (message); // Console. readKey (); // deserialization method 2 dynamic modelDy = js. deserialize <dynamic> (desJson); // deserialization string messageDy = string. format ("dynamic deserialization, ID = {0}, Name = {1}, Age = {2}, Sex = {3}", modelDy ["ID"], modelDy ["Name"], modelDy ["Age"], modelDy ["Sex"]); // the index value must be used here, and the object cannot be used. property Console. writeLine (messageDy); Console. readKey (); # endregion
The result is:
Finally, let's look at the use of JSON. NET and introduce the Class Library:
The following English cannot be understood...
Json. NET is a third party library which helps conversion between JSON text and. NET object using the JsonSerializer. the JsonSerializer converts. NET objects into their JSON equivalent text and back again by mapping. NET object property names to the JSON property names. it is open source software and free for your cial purposes. the following are some awesome [excellent] features,
- Flexible JSON serializer for converting between. NET objects and JSON.
- LINQ to JSON for manually reading and writing JSON.
- High performance, faster than. NET's built-in [embedded] JSON serializers.
- Easy to read JSON.
- Convert JSON to and from XML.
- Supports. NET 2,. NET 3.5,. NET 4, Silverlight and Windows Phone.
Let's start learning how to install and implement: In Visual Studio, go to Tools Menu-> Choose Library Package Manger-> Package Manager Console. it opens a command window where we need to put the following command to install Newtonsoft. json. install-Package Newtonsoft. jsonORIn Visual Studio, Tools menu-> Manage Nuget Package Manger Solution and type "JSON. NET "to search it online. here's the figure,
// Use the namespace to be introduced by the Json. NET class library // using Newtonsoft. Json ;//-------------------------------------------------------------------------
# Region 3. json. NET serialization List <Student> lstStuModel = new List <Student> () {new Student () {ID = 1, Name = "Zhang Fei", Age = 250, sex = "male"}, new Student () {ID = 2, Name = "Pan Jinlian", Age = 300, Sex = "female" }}; // Json. NET serialization string jsonData = JsonConvert. serializeObject (lstumodel); Console. writeLine (jsonData); Console. readKey (); // Json. NET deserialization string json = @ "{'name': 'C # ', 'age': '000000', 'id': '1', 'sex ': 'femal'} "; Student descJsonStu = JsonConvert. deserializeObject <Student> (json); // deserializes the Console. writeLine (string. format ("deserialization: ID = {0}, Name = {1}, Sex = {2}, Sex = {3}", descJsonStu. ID, descJsonStu. name, descJsonStu. age, descJsonStu. sex); Console. readKey (); # endregion
After running, the result is:
Conclusion: Try to use JSON. NET for serialization and deserialization, with good performance.
In this article we discussed about how many ways we can implement serialization/deserialization in C #. however JSON. NET wins over other implementations because it facilitates more functionality of JSON validation, JSON schema, LINQ to JSON etc. so use JSON. NET always.