Click here to Skip to main content
Click here to Skip to main content

Create JSON from C# using JSON Library

, 6 May 2010
Rate this:
Please Sign up or sign in to vote.
Create JSON from C# using JSON library available at CodePlex

Introduction

This article demonstrates how to create the JSON Object from C# code and use in JavaScript with the help of json Library.

Background 

JSON (an acronym for JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects (the “O” in “JSON”). Despite its relationship to JavaScript, it is language-independent, with parsers available for virtually every programming language. 

Now days AJAX is very famous in web development, and the response for the request created by AJAX normally returns XML. We can also return JSON from the server and the benefit is "we can use the data as object in normal OOPs." 

The Code

To convert any object or object list into JSON, we have to use the function JsonConvert.SerializeObject

The below code demonstrates the use of JSON in an ASP.NET environment: 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace JSONFromCS
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e1)
        {
            List<Employee> eList = new List<Employee>();
            Employee e = new Employee();
            e.Name = "Minal";
            e.Age = 24;

            eList.Add(e);

            e = new Employee();
            e.Name = "Santosh";
            e.Age = 24;

            eList.Add(e);

            string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);

            string script = "var employeeList = {\"Employee\": " + ans+"};";
            script += "for(i = 0;i<employeeList.Employee.length;i++)";
            script += "{";
            script += "alert ('Name : ='+employeeList.Employee[i].Name+' 
			Age : = '+employeeList.Employee[i].Age);";
            script += "}";

            ClientScriptManager cs = Page.ClientScript;
            cs.RegisterStartupScript(Page.GetType(), "JSON", script, true);
        }
    }
    public class Employee
    {
        public string Name;
        public int Age;
    }
}  

After running this program, you will get two alerts as shown in below snapshot: 

How the Code Works 

In the above example, we have created a list of Employee object and passed it to function "JsonConvert.SerializeObject". This function (JSON library) will convert the object list into JSON format. The actual format of JSON can be viewed in the below code snippet:  

{ "Maths" : [ {"Name"     : "Minal",        // First element
                             "Marks"     : 84,
                             "age"       : 23 },
                             {
                             "Name"      : "Santosh",    // Second element
                             "Marks"     : 91,
                             "age"       : 24 }
                           ],                       
              "Science" :  [ 
                             {
                             "Name"      : "Sahoo",     // First Element
                             "Marks"     : 74,
                             "age"       : 27 }, 
                             {							 
                             "Name"      : "Santosh",    // Second Element
                             "Marks"     : 78,
                             "age"       : 41 }
                           ] 
                } 

Syntax:

  • {} - acts as 'containers'
  • [] - holds arrays
  • : - Names and values are separated by a colon
  • , - Array elements are separated by commas

The same code is written to test in Windows platform, and the actual output of the library will look like: 

Points of Interest

This code is meant for intermediate programmers, who want to use C# 2.0 to create JSON and use in ASPX pages.

You can create JSON from JavaScript end, but what would you do to convert the list of object into equivalent JSON string from C#. That's why I have written this article. 

In C# 3.5, there is an inbuilt class used to create JSON named JavaScriptSerializer.   

The following code demonstrates how to use that class to convert into JSON in C#3.5.   

JavaScriptSerializer serializer = new JavaScriptSerializer()
return serializer.Serialize(YOURLIST);   

History 

  • Added advantage and usage of JSON on 6 May 2010

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jitendra Zaa
Software Developer (Senior) GlobalLogic
India India
From a Nagpur City of Maharashtra currently working as Sr. Software Engineer at GlobalLogic India pvt. Limited.
He has nearly 3 years experience and worked in many technologies like JAVA, PHP, JSP, Struts, Hibernate.
Currently working on .Net technology with C#, ASP and telerik controls.
Also has experience in cloud computing including salesforce.com.
you can reach him at ilovenagpur@gmail.com
Blog:http://www.shivasoft.in/blog

Comments and Discussions

 
GeneralKnow your javascript before you write about it Pinmemberzpslva6-May-10 0:31 
GeneralRe: Know your javascript before you write about it PinmemberJitendra Zaa6-May-10 0:58 
GeneralRe: Know your javascript before you write about it PinmemberCraig G. Wilson6-May-10 1:44 
GeneralRe: Know your javascript before you write about it PinmemberJitendra Zaa6-May-10 2:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 6 May 2010
Article Copyright 2010 by Jitendra Zaa
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid