Several ways to implement JSON serialization and deserialization in C # _c# Tutorials

Source: Internet
Author: User
Tags data structures json net serialization serialization visual studio

What is JSON?

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. The JSON is a text format this is completely language independent.

Translation: Json "JavaScript Object representation", it is a lightweight data interchange format, we can read and write it very easily, and it is easy to be transformed and generated by the computer, it is completely independent of the language.

JSON supports the following two types of data structures:

    1. A collection of key-value pairs--a variety of programming languages that support this data structure;
    2. A collection of ordered list-type values-this includes arrays, collections, vectors, or sequences, and so on.

JSON has some of the following forms of expression

1. The object

A "key/value" with no order, an object that starts with a curly brace "{" and ends with a curly brace "}", followed by a colon at the end of each "key", and a comma is used to separate multiple key-value pairs.

For example:

  

2. Array

Sets the order of values, an array that starts with the bracket "[" and ends with the 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 separated with backslashes.

For example:

 
 

All right, let's talk about JSON.

There are three ways of serializing and deserializing:

    1. Use JavaScriptSerializer class
    2. Use DataContractJsonSerializer class
    3. Using the Json.NET class library

Let's take a look at the use of DataContractJsonSerializer first.

DataContractJsonSerializerClass helps us serialize and deserialize JSON, and he System.Runtime.Serialization.dll 's in the namespace under the Assembly System.Runtime.Serialization.Json .

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 has to be DataContractJsonSerializer added using serialization and deserialization, and it is not necessary to add to the other two ways.

The Code of our program:

To refer to the assembly before introducing this namespace

/----------------------------------------------------------------------------- -----------------//Use DataContractJsonSerializer method to introduce the namespaces in System.Runtime.Serialization.dll. Using
System.Runtime.Serialization.Json; //--------------------------------------------------------------------------------------------
#region 1.DataContractJsonSerializer serialization and deserialization of Student stu = new Student () {ID = 1, Name = "Cao", S
   ex = "Male", age = 1000};
   Serialization of DataContractJsonSerializer js = new DataContractJsonSerializer (typeof (Student));
   MemoryStream msobj = new MemoryStream (); Writes the JSON-formatted data after serialization to JS in the stream.
   WriteObject (Msobj, Stu);
   msobj.position = 0;
   Starting at 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);
   Deserializes string todes = JSON;
   String to = "{\ id\": \ "1\", \ "name\": \ "Cao", \ "sex\": \ "men \", "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:

Then 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 the A. Net object to JSON string with serialize method. It ' s possible to deserialize JSON string to. Net object using Deserialize<t> or Deserializeobject methods. Let ' s, implement serialization and deserialization using JavaScriptSerializer.

Here we have to quote

/----------------------------------------------------------------------------- ------------//Using the JavaScriptSerializer method requires the introduction of the namespace, which is System.Web.Extensions.dll in the assembly. Using
System.Web.Script.Serialization; //----------------------------------------------------------------------------------------
#region 2.JavaScriptSerializer method for serialization and deserialization
   Student stu = new Student ()
    {
     ID = 1,
     Name = "Guan Yu", Age
     = 2 ,
     Sex = "male"
    };

   JavaScriptSerializer js = new JavaScriptSerializer ();
   String jsondata = js. Serialize (stu);//Serialization
   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 a
   string messagedy = string. Format ("Dynamic deserialization, id={0},name={1},age={2},sex={3}",
    modeldy["ID"], modeldy["Name"], modeldy["age"], modeldy[" Sex "]);//Here you can use index values, and you cannot use objects. Property
   Console.WriteLine (messagedy);
   Console.readkey (); 
   

The result:

Finally look at the use of json.net, the introduction of the class Library:

The following English, can not read the 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 into their JSON equivalent-text and back again by mapping the. NET Object Propert Y names to the JSON property names. It is the open source software and free for commercial 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 "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-> Manager Console. It opens a command window where we need the following command to install Newtonsoft.json.

Install-package Newtonsoft.json
OR
In Visual Studio, Tools menu-> Manage Nuget Package manger Solution and type ' json.net ' to search it online. Here ' s the figure,

Namespaces
//-----------------------------------------------------------------------------
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= "Men"},
   new Student () {id=2,name= "Jin Lian", age=300,sex= "female"}
   };

   Json.NET serialized
   String jsondata = Jsonconvert.serializeobject (Lststumodel);

   Console.WriteLine (jsondata);
   Console.readkey ();


   Json.NET
   String json = @ "{' Name ': ' C # ', ' Age ': ' 3000 ', ' 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:

Summarize

Finally, the use of json.net to serialize and deserialization, good performance.

In this article we discussed about how to many ways we can implement Serialization/deserialization in C #. However Json.NET wins over the other implementations because it facilitates more functionality of JSON validation, JSON schema , LINQ to JSON etc. So use json.net always.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.

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.