28% de descuento del curso en SQL Server

Estrada Web Group Estrada Web Group
Serialización JSON C#
Estrada Web Group
Estrada Web Group
Estrada Web Group Estrada Web Group
Calificar:
16 abril Javascri..

Serialization and deserialization JSON with C #

Serialization and deserialization JSON with C #

json to c#

Nowadays, we are dealing with JSON data mostly when receiving data in JSON format from a web service and getting data from it. To accomplish getting data from JSON or creating JSON text from a custom object we will use JSON serialization and deserialization in C#.
 
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. JSON is a text format that is completely language independent. 
 
JSON supports the following two data structures,
  • Collection of name/value pairs - This Data Structure is supported by different programming languages.
  • Ordered list of values - It includes array, list, vector or sequence etc. 

Examples JSON

  • Object

An unordered "name/value" assembly. An object begins with "{" and ends with "}". Behind each "name", there is a colon. And comma is used to separate much "name/value". For example,

 var usuario = { "nombre" : "Manas" , "género" : "Hombre" , "cumpleaños" : "1987-8-8" }
  • Array

Value order set. An array begins with "[" and end with "]". And values are separated with commas. For example,

 var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}}, {"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]
  • String

Any quantity Unicode character assembly which is enclosed with quotation marks. It uses backslash to escape.

 var userlist = "{\"ID\":1,\"Name\":\"Manas\",\"Address\":\"India\"}" 
We can implement JSON Serialization/Deserialization in the following three ways:
  • Using JavaScriptSerializer class
  • Using DataContractJsonSerializer class
  • Using JSON.NET library 

Using 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 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.
 
Following code snippet is to declare custom class of Blog type.
 class Blog 
{ 
public string Name { get; set; } 
public string Description { get; set; } 
} 
Serialization
 
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of Blog class and assigns some values to its properties. Then we create an instance of JavaScriptSerializer and call Serialize() method by passing object(Blog). It returns JSON data in string format.
 // Creating Blog object 
Blog bsObj = new Blog () 
{ 
Name = "estradawebgroup", 
Description = "Compartir conocimiento" 
}; 
 // Serializing object to json data 
JavaScriptSerializer js = new JavaScriptSerializer(); 
string jsonData = js.Serialize(bsObj); 
// {"Name":" estradawebgroup ","Description":" Compartir conocimiento "}

 

Deserialization
 
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it creates JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns custom object (Blog) from JSON data.
 // Deserializing json data to object 
JavaScriptSerializer js = new JavaScriptSerializer(); 
Blog blogObject = js.Deserialize<Blog>(jsonData); 
string name = blogObject.Name; 
string description = blogObject.Description; 
// Other way to whithout help of Blog class 
dynamic blogObject = js.Deserialize<dynamic>(jsonData); 
string name = blogObject["Name"]; 
string description = blogObject["Description"]; 

 

Using DataContractJsonSerializer
 
DataContractJsonSerializer class helps to serialize and deserialize JSON. It is present in namespace System.Runtime.Serialization.Json which is available in assembly System.Runtime.Serialization.dll. Using the class we can serialize an object into JSON data and deserialize JSON data into an object.

Let's say there is Employee class with properties such as name, address and property values also assigned. Now we can convert the Employee class instance to JSON document. This JSON document can be deserialized into the Employee class or another class with an equivalent data contract. The following code snippets demonstrate about serialization and deserialization.
 
Let's create a custom class Blog for serialization and deserialization,
 [DataContract] 
class Blog 
{ 
[DataMember] 
public string Name { get; set; } 
[DataMember] 
public string Description { get; set; } 
} 
Serialization
 
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of Blog class and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter Blog class and create an instance of MemoryStream class to write object(Blog). Lastly it creates an instance of StreamReader class to read JSON data from MemorySteam object.
 Blog bsObj = new Blog () 
{ 
Name = "estradawebgroup", 
Description = " Compartir conocimiento " 
}; 
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Blog)); 
MemoryStream msObj = new MemoryStream(); 
js.WriteObject(msObj, bsObj); 
msObj.Position = 0; 
StreamReader sr = new StreamReader(msObj); 
// "{\"Description\":\" Compartir conocimiento \",\"Name\":\"estradawebgroup\"}" 
string json = sr.ReadToEnd(); 
sr.Close(); msObj.Close(); 

 

Deserialization
 
In Deserialization, it does the opposite of Serialization, which means it converts JSON string to a custom .Net object. In the following code, it creates an instance of Blog class and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter Blog class and creating an instance of MemoryStream class to write object(Blog). Lastly it creates an instance of StreamReader class to read JSON data from MemorySteam object.
 string json = "{\"Description\":\" Compartir conocimiento \",\"Name\":\"estradawebgroup\"}"; 
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { // Deserialization from JSON 
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Blog)); 
Blog bsObj2 = (Blog)deserializer.ReadObject(ms); 
Response.Write("Name: " + bsObj2.Name); // Name: estradawebgroup 
Response.Write("Description: " + bsObj2.Description); // Description: Compartir conocimiento } 
Using Json.NET
 
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 property names to the JSON property names. It is open source software and free for commercial purposes.
 
The following are some awesome 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 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.Json
OR
In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. Here's the figure,
json.net
Serialization
 
In Serialization, it converts a custom .Net object to a Json string. In the following code, it creates an instance of Blog class and assigns some values to its properties. Then it calls static method SerializeObject() of JsonConvert class by passing object(Blog). It returns JSON data in string format.
 // Creating Blog object 
Blog bsObj = new Blog () 
{ 
Name = "estradawebgroup", 
Description = "Compartir conocimiento" }; // Convert Blog object to JOSN string format 
string jsonData = JsonConvert.SerializeObject(bsObj); 
Response.Write(jsonData); 
Deserialization
 
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it calls static method DeserializeObject() of JsonConvert class by passing JSON data. It returns custom object (Blog) from JSON data.
string json = @ "{ 'Nombre' : 'estradawebgroup’, 'Descripción' : 'Compartir conocimiento' } "; 
Blog bsObj = JsonConvert.DeserializeObject <Blog> (json); 
Response.Write (bsObj.Name);

Compartir:

Cargando...
Descarga el código fuente

Obten el código del sistema de gestión de proyectos.

Shape