Click here to Skip to main content
15,881,413 members
Articles / Programming Languages / Javascript

Create JSON from C# using JSON Library

Rate me:
Please Sign up or sign in to vote.
4.66/5 (24 votes)
6 May 2010CPOL2 min read 447.5K   22.3K   54   14
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: 

C#
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:  

C#
{ "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.   

C#
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)


Written By
Software Developer (Senior) Cognizant Technology Solutions
India India
Having more than 9 years of experience in Programming and web application development.

Writing technical blog articles, learning new Programming languages , frameworks and sharing knowledge with others is one of my hobby. The more I learn, more I understood that how little I know and that drives me to dig into technology and languages to explore.

From last few years now, working on Salesforce platform and providing customer solutions using force.com as an Architect and Technical Lead Role. I have worked on many area of Salesforce like force.com, Heroku, PHP Toolkit, Partner Webservices, Metadata and Enterprise webservices, Tooling API, Customer Portal, Partner Portal, Community, Salesforce1 etc...

Blog:http://www.jitendrazaa.com/blog

Comments and Discussions

 
Questionwhats realy longer or shorter Pin
Member 137031891-Mar-18 1:04
Member 137031891-Mar-18 1:04 
so do you realize this sounds like alota extra jargon?basicly it sounds like your adding a secondary list to describe an item in place of the actual item.. its like take a doll to count as a doll house instead of haveing sent the full house ..oh then wrap the doll in some guardian assisters to keep it in a straight line with shackles.then more process just to get back to what the item was before it got transformed into a text so thats alota extra bits for every letter or number just represent a dot that was only a dot. but then converted into a longer <.> then some number to say how many bits make that dot. however i do understand shorthanding 10000/10101010/000111000110 into somthin like 1+3'0/4x10/ excetra, if thats shorthanding the data then the item should still show up as the original item instead of the text form because that should just be simply converting the background digits into a shorter formula hints changeing away from the longer 1s and zeros where just as originaly you would not see the backgound text digits but the single name of item and its image which would be faster than even veiwing the script.. then needing a 3rd app to open it then a 4th to convert it back to the simple item that already showed as its name and the picture which was faster in simply moveing the item after haveing compressed it into its shorter hand transfer digits where item name-1300x1300 was the shorter than name colon parentheses dash capsolated 2 times for every detail capsolated and dashed divided slash bs for every single picture compared to simply shorty-1300x1300 and the image itself as a jpg already shows ,,,again consider heres a painting now take a note book measure it count alll the colors assign collor codes the every centimeter but put all that in a list down the page and what seems longer? the squared pixelated blocky image rebuild flated out from its color depth or thousand set digits you never see except as the color in its location then the depth like xraying an ink layer of how we see curves in the chemicals by the actual microbial depths rather than the flat blocked rebuild.. kinda makes json files seem like alota jargon text when used in place of actualy leaveing it in the background and simpley getting the image item sought to show directly as it was but now i got a bunch of dang json files that i cant do crap with to see the original dang images so what the hell with this dang junk ,,,!!!!can anyone fix this kinda crap ? exactly why i hate json files how bout tranfers automaticly compress zip shorthand but automaticly show straight without haveing to go through more process to locate then zip then unzip then reconvert jsons to the item intended in the first place so item is itself appears as on thing and moves as the one thing on drag and drop or copy command

and trash the hundred other bs steps!!!!
GeneralMy vote of 1 Pin
karvikpadhya13-Feb-13 13:39
karvikpadhya13-Feb-13 13:39 
QuestionWhat if i dont want to serialise/deserialise my entire object? Pin
rbw.sheena21-Jul-11 5:54
rbw.sheena21-Jul-11 5:54 
GeneralMy vote of 2 Pin
hiren.daftari25-May-11 20:27
hiren.daftari25-May-11 20:27 
GeneralJSON Parser Pin
jitendraZaa5-May-11 19:59
jitendraZaa5-May-11 19:59 
GeneralMy vote of 1 Pin
zpslva6-May-10 0:32
zpslva6-May-10 0:32 
GeneralKnow your javascript before you write about it Pin
zpslva6-May-10 0:31
zpslva6-May-10 0:31 
GeneralRe: Know your javascript before you write about it Pin
Jitendra Zaa6-May-10 0:58
Jitendra Zaa6-May-10 0:58 
GeneralRe: Know your javascript before you write about it Pin
Craig G. Wilson6-May-10 1:44
Craig G. Wilson6-May-10 1:44 
GeneralRe: Know your javascript before you write about it Pin
Jitendra Zaa6-May-10 2:48
Jitendra Zaa6-May-10 2:48 
GeneralMy vote of 1 Pin
Munim Abdul5-May-10 21:20
Munim Abdul5-May-10 21:20 
GeneralRe: My vote of 1 Pin
Jitendra Zaa6-May-10 0:55
Jitendra Zaa6-May-10 0:55 
General[My vote of 2] Im not going to vote this down but..... Pin
Argyle4Ever5-May-10 10:00
Argyle4Ever5-May-10 10:00 
GeneralRe: [My vote of 2] Im not going to vote this down but..... Pin
Jitendra Zaa5-May-10 20:03
Jitendra Zaa5-May-10 20:03 

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

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