In C #, the serialization and deserialization of JSON is summarized in several ways

Source: Internet
Author: User
Tags net serialization

    • What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans-read and write and easy-machines to parse and generate. JSON is a text format, which is completely language independent.

Translation: Json "JavaScript Object Presentation method", it is a lightweight data interchange format, we can easily read and write it, and it is easily converted and generated by the computer, it is completely independent of the language.

JSON supports the following two types of data structures:

    • The collection of key-value pairs--a variety of different programming languages, supports this data structure;
    • A collection of ordered list-type values-this includes arrays, collections, vectors, or sequences, and so on.

JSON has several forms of expression

1. Objects

A "key/value" with no order, an object starting with curly braces "{" and ending with curly braces "}", followed by a colon after each "key", and using commas to separate multiple key-value pairs. For example:

var user = {"name": "Manas", "Gender": "Male", "Birthday": "1987-8-8"}

2. Arrays

To set the order of values, an array begins with the brackets "[" and ends in 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, marked with quotation marks, and delimited with backslashes. For example:

var userlist = "{\" id\ ": 1,\" name\ ": \" Manas\ ", \" address\ ": \" India\ "}"

Well, after we're done with JSON, here's the point, there are three ways to serialize and deserialize in advance:

1. Using the JavaScriptSerializer class

2. Using the DataContractJsonSerializer class

3. Using the Json.NET class library

Let's take a look at the situation with DataContractJsonSerializer.

The DataContractJsonSerializer class helps us serialize and deserialize JSON, which he has in the Assembly System.Runtime.Serialization.dll under the System.Runtime.Serialization.Json namespace.

First, here, I create a new console program, create a new 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],[datacontract] in the student entity above is required to be added using DataContractJsonSerializer serialization and deserialization, and it is not necessary for the other two methods to be added.

Code for our program:

To refer to an assembly before introducing this namespace

----------------------------------------------------------------------------------------------//Use Datacontractjsonseria The Lizer method requires the introduction of namespaces in System.Runtime.Serialization.dll. Using system.runtime.serialization.json;//----------------- ---------------------------------------------------------------------------
Serialization and deserialization of the #region 1.DataContractJsonSerializer mode Student stu = new Student () {ID = 1            , Name = "Caocao", Sex = "male", age = 1000};            Serialization of DataContractJsonSerializer js = new DataContractJsonSerializer (typeof (Student));            MemoryStream msobj = new MemoryStream (); Writes the serialized JSON format data to the stream JS.            WriteObject (Msobj, Stu);            msobj.position = 0;            Starting from 0 This position reads the data in the stream StreamReader sr = new StreamReader (msobj, Encoding.UTF8); String json = Sr.            ReadToEnd (); Sr.            Close ();            Msobj.close ();            Console.WriteLine (JSON);            Deserialization of string todes = JSON;            String to = "{\" id\ ": \" 1\ ", \" name\ ": \" Cao ", \" sex\ ": \" male \ ", \" age\ ": \" 1230\ "}";  using (var ms = new MemoryStream (Encoding.Unicode.GetBytes (todes))) {DataContractJsonSerializer Deseralizer = NEW DataContractJsonSerializer (typeof (Student)); Student model = (Student) deseralizer.                ReadObject (MS);///Deserialization ReadObject Console.WriteLine ("id=" + model.id); Console.WriteLine ("Name=" + model.                Name); Console.WriteLine ("Age=" + model.                Age); Console.WriteLine ("sex=" + model.            SEX);             } console.readkey (); #endregion

After running the result is:

And 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 are available in assembly System.Web.Extensions.dll. To serialize A. Net object to JSON string, use Serialize method. It's possible to deserialize JSON string to. Net object using Deserialize<t> or Deserializeobject methods. Let's see how to implement serialization and deserialization using JavaScriptSerializer.

This is the first reference to

-----------------------------------------------------------------------------------------//Use the JavaScriptSerializer method to introduce namespace, this is in assembly System.Web.Extensions.dll. Using system.web.script.serialization;//-------------------------------- --------------------------------------------------------
Serialization and deserialization #region 2.JavaScriptSerializer mode Student stu = new Student () {ID = 1            , Name = "Guan Yu", age = +, Sex = "Male"};            JavaScriptSerializer js = new JavaScriptSerializer (); String jsondata = js.            Serialize (stu);//Serialization of Console.WriteLine (Jsondata);            Deserialization mode One: 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 Mode 2 Dynamic Modeldy = js. Deserialize<dynamic> (Desjson); Deserializes string messagedy = string. Format ("Dynamic deserialization, id={0},name={1},age={2},sex={3}", modeldy["ID"], modeldy["Name"], modeldy["age"], modeldy[" Sex "]);//Use the index hereValue, the object cannot be used. Attribute Console.WriteLine (messagedy);             Console.readkey (); #endregion

The result is:

Finally, take a look at the use of json.net and introduce a class library:

The following English, can not read to skip ...

Json.NET is a third party library which helps conversion between JSON text and. NET object using the Jsonserializer. The Jsonserializer converts. NET objects to their JSON equivalent text and back again by mapping the. NET Object Propert Y names to the JSON property names. It is open source software and free for commercial purposes. The following is 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 "inline" 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,

Namespaces that need to be introduced using 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 of            string jsondata = Jsonconvert.serializeobject (Lststumodel);            Console.WriteLine (jsondata);            Console.readkey ();            Json.NET deserialization of            string json = @ "{' Name ': ' C # ', ' Age ': ' n ', ' ID ': ' 1 ', ' Sex ': ' Female '}";            Student Descjsonstu = jsonconvert.deserializeobject<student> (JSON);//Deserialization            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:

Summary: Finally, the best use of json.net to serialize and deserialize, 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. Json.NET always.

In C #, the serialization and deserialization of JSON is summarized in several ways

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.