How To Create JSON In C#

In this article, you will get the following questions answered.

  • What is JSON?
  • What is serialization and deserialization of JSON data?
  • How many preferred types of JSON data are there?
  • Step by step JSON creation.

What is JSON?

JSON's full form is JavaScript Object Notation.

JavaScript Object Notation (JSON) is a lightweight data-interchange format. JSON creation and read of JSON string is very easy. In Web technology, nowadays people transfer and receive the data in this format. Even MONGO DB stores the data in JSON format.

What is serialization and deserialization of JSON data?

Creation of JSON data from an object is serialization, and deserialization is its inverse operation.

How many preferred types of JSON data are there?

Preferred types of JSON Data are as following,

Object

In this, the data is stored in KEY/VALUE pattern. Object starts with { and end with }. It is very easy to read and understand the object.

As you see in the example section, Key “friendid” and value “1”, which is separated by : colon sign.

Example

  1. {"friendid":"1","friendname":"Ashish Kalla","friendplace":"Malad","friendmobile":"777777777"}   

Array

Array starts with “[“ and end with “]”and the rest of the operation is similar to the object pattern. JSON array is mostly the same as a general list kind of array, which we use in .NET. In addition to it in Javascript, you can plugin function to process something.

Example 

  1. Var friendlist=[{"friendlist":{"friendid":"2","friendname":"Ashish Kalla","friendplace":"Malad","friendmobile":"777777777"}},  
  2.   
  3. {"friendlist":{"friendid":"3","friendname":"Suhana Kalla","friendplace":"Phalodi","friendmobile":"666666666"}}]   

Step by step JSON creation 

JSON is used primarily to transmit the data between a Server and Web Application. Basically in .NET, we can send and receive JSON data. In my major projects, I transfer/give JSON. We give/ send/ transfer JSON data through Web Service, AJAX jQuery calls and other ways.

Here, we generate JSON data in C# code at the back-end and return the string. You can return JSON in object mode (single record) or an array mode (list of records).

Step by Step JSON creation

In this walk through, we create JSON data and write on the Browser screen, using Response.Write().

Step 1

Create ASP.NET Empty Web Site project named “JsonData”.


Step 2

Create a table and code the sample data.

Table structure 

  1. USE [MBKTest]  
  2. GO  
  3.   
  4. SET ANSI_NULLS ON  
  5. GO  
  6.   
  7. SET QUOTED_IDENTIFIER ON  
  8. GO  
  9.   
  10. CREATE TABLE [dbo].[tblMyFriends](  
  11.     [FriendID] [int] IDENTITY(1,1) NOT NULL,  
  12.     [FriendName] [nvarchar](50) NULL,  
  13.     [FriendPlace] [nvarchar](50) NULL,  
  14.     [FriendMobile] [nvarchar](10) NULL  
  15. ON [PRIMARY]  
  16.   
  17. GO   

Sample data


Step 3

Right click on the project and select Add-->Add New Item and select WebForm


Add a new Web Form named “Default.aspx”, in this page accepting user Id and password as well as creating cookies.


Step 4

Right click on the project and select Add-->Add New Item and select [Linq To SQL Class].


Select LINQ to SQL Class named “FriendListDataClass.dbml”


As you click on ADD button in the screen given above, you will see the dialog box.


Simply press YES.

Now, switch to Server Explorer and select Data Connections.

Step 5

Connection establishment

Right click on Data Connections and select ADD CONNECTION option.


Double click your DBML file, which is located inside APP_CODE folder.

Drag and drop the table named “ tblMyFriends” on DBML canvas.


Understanding code for JSON creation

To achieve the task, we require the namespace given below.

  1. System.IO;  
  2. System.Runtime.Serialization.Json;  
  3.   
  4. //this line very important which make ready program to make JSON  
  5. //GetType giving idea about you are going to create json for "System.Collections.Generic.List`1[tblMyFriend]"  
  6. DataContractJsonSerializer ser = new DataContractJsonSerializer(FriendList.GetType());  
  7.           
  8. //Writing the JSON  
  9. ser.WriteObject(str, FriendList);   

CODE Default.aspx.cs 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Runtime.Serialization.Json;  
  6. using System.Web;  
  7. using System.Web.UI;  
  8. using System.Web.UI.WebControls;  
  9.   
  10. public partial class _Default : System.Web.UI.Page  
  11. {  
  12.     protected void Page_Load(object sender, EventArgs e)  
  13.     {  
  14.         string JsonStr = null;  
  15.        
  16.         FriendListDataClassDataContext db = new FriendListDataClassDataContext();  
  17.         var FriendList = db.tblMyFriends.ToList();  
  18.   
  19.         MemoryStream str = new MemoryStream();  
  20.   
  21.         //this line very important which make ready program to make JSON  
  22.         //GetType giving idea about you are going to create json for "System.Collections.Generic.List`1[tblMyFriend]"  
  23.         DataContractJsonSerializer ser = new DataContractJsonSerializer(FriendList.GetType());  
  24.           
  25.         //Writing the JSON  
  26.         ser.WriteObject(str, FriendList);  
  27.   
  28.         str.Position = 0;  
  29.         StreamReader sr = new StreamReader(str);  
  30.         JsonStr = sr.ReadToEnd();  
  31.   
  32.         //Writing the JSON on browswer   
  33.         Response.Write(JsonStr);  
  34.           
  35.     }  
  36. }   

OUPUT

JSON DATA

  1. [{"FriendID":1,"FriendMobile":"999999786","FriendName":"Shree Sai","FriendPlace":"Shirdi"},{"FriendID":2,"FriendMobile":"777777777","FriendName":"Ashish Kalla","FriendPlace":"Malad"},{"FriendID":3,"FriendMobile":"666666666","FriendName":"Suhana Kalla","FriendPlace":"Phalodi"},{"FriendID":4,"FriendMobile":"555555555","FriendName":"Aakash Kalla","FriendPlace":"Malar"},{"FriendID":5,"FriendMobile":"111111111","FriendName":"Mahesh Sir","FriendPlace":"US"},{"FriendID":6,"FriendMobile":"222222222","FriendName":"Praveen Sir","FriendPlace":"Singapore"},{"FriendID":7,"FriendMobile":"333333333","FriendName":"Dinesh Sir","FriendPlace":"Dubai"}]  

 

Up Next
    Ebook Download
    View all
    Learn
    View all