dcsimg

WEBINAR:
On-Demand

Application Modernization: What Is It and How to Get Started


Introduction

JSON (JavaScript Object Notation) is a lightweight data interchanging format. It's based on a subset of the JavaScript language. JSON is a text format and it is completely language independent. JSON is easy for humans to read and write, and it's easy for code to parse and generate. It's an alternative to XML, natively supporting basic data types. The syntax that is used in JavaScript and JSON itself stands for "JavaScript Object Notation."

JSON is built on two structures:

  • A collection of name/value pairs. In different languages, this is realized as an object, record, structure, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, JSON is realized as an array, vector, list, or sequence.

In this article, I will explain about the JSON Serialization and Deserialization features with examples.

Why JSON?

We are mostly dealing with JSON while requesting or receiving data with a REST service. To accomplish getting data from JSON or creating JSON text from a custom object, we will use JSON serialization and deserialization in C#.

JSON supports the following styles.

Object

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

var user = {"name":"Tapas","gender":"Male","birthday":"1991-1-1"}

Array

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

var userlist = [{"user":{"name":"Tapas","gender":"Male",
   "birthday":"1991-1-1"}}, {"user":{"name":"Tapas","Male":"Male",
   "birthday":"1991-1-1"}}]

String

A string is any quantity Unicode character assembly which is enclosed with quotation marks. It uses a backslash to escape.

var userlist = "{\"ID\":1,\"Name\":\"Tapas\",\"Address\":
   \"Kolkata,India\"}"

What Is Json.NET?

Json.NET is a popular high-performance third-party JSON framework for .NET. It's an open source software and is free for commercial purposes. Json.NET supports .NET 2, .NET 3.5, .NET 4.5, Silverlight, and Windows Phone. It helps conversion between JSON text and .NET objects by using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent text. The Deserialization process converts it to a .NET object and back again by mapping the .NET object property names to the JSON property names. Json.NET can convert LINQ to JSON for manually reading and writing JSON. Also, for easy JSON reading, developers can use Json.NET.

To install Json.NET, open Visual Studio and go to Tools Menu -> Choose Library Package Manger -> Package Manager Console. This opens a command window where we need to put in the following command to install Newtonsoft.Json.

Install-Package Newtonsoft.Json:

To install from a NuGet Package, open Visual Studio, Tools menu -> Manage NuGet Package Manger Solution, and type "JSON.NET" to search for it online. Refer to Figures 1 and 2.

Adding a NuGet Package from Visual Studio
Figure 1: Adding a NuGet Package from Visual Studio

Selected a NuGet Package from Visual Studio
Figure 2: Selected a NuGet Package from Visual Studio

JSON Serialization with an Example

Serialization converts a .NET object to JSON formatted text. For example, there is a student object holding data and we need to convert the object to JSON format. To demonstrate JSON serialization, I have created a student class with Roll number, Name, Address, and other properties. I will utilize this class in coming sections of this article. Refer to the following source code.

public class Student

   public int Rollnumber { get; set; }
   public string StudentName { get; set; }
   public string StudentAddress { get; set; }
   public string Class { get; set; }
   public DateTime StudentDOB { get; set; }
   public string StudentSubject { get; set; }
}

Next, I have created an object of the student class and assigned the required value to its properties. Then, I called the SampleJSONSerilaize () function. It prints the JSON object in the response stream. Here is the code:

   private void SampleJSONSerilaize()
   {
      Student objStudent = new Student();
      objStudent.Rollnumber = 1;
      objStudent.StudentName = "Tapas";
      objStudent.StudentAddress = "Kolkata, India";
      objStudent.Class = "X";
      objStudent.StudentDOB = DateTime.Now;
      objStudent.StudentSubject = "Sample";
      string objjsonData = JsonConvert.SerializeObject(objStudent);
      Response.Write(objjsonData );
   }

JSON Deserialization with an Example

Deserialization is the process of converting a string into an in-memory instance of an object. Basically, it's the opposite process of the JSON serialization we discussed in the previous section. JSON deserialization converts JSON formatted text to .NET objects. In our example, we have a string value in JSON format text that holds information about a student. In the following example, we will convert that JSON text to a .NET student object.

private void SampleJSONDeserilaize()
{
   string json = @"{
      'Rollnumber': '1',
      'StudentName': 'Tapas',
      'StudentAddress': 'Kolkata, India',
      'Class' : 'X',
      'StudentDOB' : 12/12/2001,
      'StudentSubject' : 'Sample Subject'
   }";
   Student objStudent = JsonConvert.DeserializeObject
      <Student>(json);
   Response.Write(objStudent.StudentName);
}

Conclusion

I hope this article has provided you with a basic understanding about Json.NET and how it is helpful to serialize and deserialize an object in ASP.NET. That's all for today. Happy Reading.



About the Author

Tapas Pal

I am working in Microsoft Technology for last 15 years and presently working with Cognizant Technology Solutions, India as Senior Architect. I have completed TOGAF 9.1,Microsoft Certification on .NET 1.1 , .NET 2.0, SQL Server 2005 and Sharepoint. Please visit my Blog - http://tapas-pal.blogspot.com/

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date