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.
JSON has following styles,
- 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 user = {"name":"Manas","gender":"Male","birthday":"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
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 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 BlogSite for serialization and deserialization,
- [DataContract]
- class BlogSite
- {
- [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 BlogSiteclass and assigns values to its properties. Then
we create an instance of DataContractJsonSerializer class by passing the
parameter BlogSite class and create an instance of MemoryStream class to write
object(BlogSite). Lastly it creates an instance of StreamReader class to read
JSON data from MemorySteam object.
- BlogSite bsObj = new BlogSite()
- {
- Name = "DotnetOffice",
- Description = "Share Knowledge"
- };
-
- DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(BlogSite));
- MemoryStream msObj = new MemoryStream();
- js.WriteObject(msObj, bsObj);
- msObj.Position = 0;
- StreamReader sr = new StreamReader(msObj);
-
- // "{\"Description\":\"Share Knowledge\",\"Name\":\"DotnetOffice\"}"
- 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 BlogSite
class and assigns values to its properties. Then we create an instance of
DataContractJsonSerializer class by passing the parameter BlogSite class and
creating an instance of MemoryStream class to write object(BlogSite). Lastly it
creates an instance of StreamReader class to read JSON data from MemorySteam
object.
- string json = "{\"Description\":\"Share Knowledge\",\"Name\":\"DotnetOffice\"}";
-
- using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
- {
- // Deserialization from JSON
- DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite));
- BlogSite bsObj2 = (BlogSite)deserializer.ReadObject(ms);
- Response.Write("Name: " + bsObj2.Name); // Name: DotnetOffice
- Response.Write("Description: " + bsObj2.Description); // Description: Share Knowledge
- }
-
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 or DeserializeObject methods. Let's see how to implement
serialization and deserialization using JavaScriptSerializer.
Following code
snippet is to declare custom class of BlogSites type.
- class BlogSites
- {
- 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 BlogSiteclass and assigns some values to its properties.
Then we create an instance of JavaScriptSerializer and call Serialize() method by
passing object(BlogSites). It returns JSON data in string format.
- // Creating BlogSites object
- BlogSites bsObj = new BlogSites()
- {
-
Name = "DotnetOffice",
-
Description = "Share Knowledge"
- };
-
- // Serializing object to json data
- JavaScriptSerializer js = new JavaScriptSerializer();
- string jsonData = js.Serialize(bsObj); // {"Name":"DotnetOffice","Description":"Share Knowledge"}
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
(BlogSites) from JSON data.
- // Deserializing json data to object
- JavaScriptSerializer js = new JavaScriptSerializer();
- BlogSites blogObject = js.Deserialize
(jsonData); - string name = blogObject.Name;
- string description = blogObject.Description;
-
- // Other way to whithout help of BlogSites class
- dynamic blogObject = js.Deserialize
(jsonData); - string name = blogObject["Name"];
- string description = blogObject["Description"];
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,
Serialization
In Serialization,
it converts a custom .Net object to a Json string. In the following code, it
creates an instance of BlogSiteclass and assigns some values to its properties.
Then it calls static method SerializeObject() of JsonConvert class by passing
object(BlogSites). It returns JSON data in string format.
- // Creating BlogSites object
- BlogSites bsObj = new BlogSites()
- {
- Name = "DotnetOffice",
- Description = "Share Knowledge"
- };
-
- // Convert BlogSites 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 (BlogSites) from JSON data.
- string json = @"{
- 'Name': 'DotnetOffice',
- 'Description': 'Share Knowledge'
- }";
- BlogSites bsObj = JsonConvert.DeserializeObject
(json); -
- Response.Write(bsObj.Name);
Conclusion
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.
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.
EmoticonEmoticon